Home > Net >  A generic CPU non blocking way to handle while loop in C
A generic CPU non blocking way to handle while loop in C

Time:04-08

I would ask a very generic question that has been perplexing me for some time. Very, very often we have to wait for the results from non-blocking functions, for example bytes to read from a file, socket or device.

Why waste the godsend of non-blocking functions for a blocking while?

So, is it possible, at least in POSIX API, to do a sort of while(!somethingToRead()) forceToPassToNextJobInScheduler();?

I can't find information about this anywhere, and it would be beautiful to limit the use of threads.

The fact that I have not found anything suggests to me that either I have not used the right keywords or that nothing similar is possible. But it would be wonderful, I hope.

CodePudding user response:

I finally found the answer to the question thanks the researcher behind libvpoll: the exactly function that I'm talking about with 'forceToPassToNextJobInScheduler' is sched_yield(): https://man7.org/linux/man-pages/man2/sched_yield.2.html

I'm pretty gone near to the solution, having open a tab aboust sched functions: https://man7.org/linux/man-pages/man7/sched.7.html But as not a low-level POSIX expert, it's difficult to find easily the right solution.

CodePudding user response:

You don't need this. This is already what blocking does. When your process is blocked, the scheduler automatically runs the next job/process/thread that is not blocked.

If you write a loop like this, the only difference will be that the scheduler thinks your thread isn't blocked, and it will keep switching back to your thread and then your thread will keep switching back the the scheduler - a waste of time.

Better to use actual blocking, and then the scheduler will know your thread is blocked, and won't run it until it's unblocked.

Why waste the godsend of non-blocking functions for a blocking while?

You don't. To make good use of non-blocking functions you have to write your entire program in a non-blocking way, probably using a struct per connection instead of a thread, and something like epoll to see which connections have new data.

  • Related