Best practise is not to poll…but isn’t polling happening internally anyway when a thread calls wait()

locksmultithreadingparallelism

Say we have some thread that wants to check when another thread is finished its task. I have read that we should call a wait() type function that will make this thread wait until it receives a notification that the other thread is finished. And that this is good because it means we aren't performing expensive polling.

But isn't polling happening internally at a lower level anyway? I.e. if we make the thread wait() isn't the kernal performing polling anyway to check when the other thread is finished so that it can then notify the first thread?

I presume I a missing out on something here, can someone enlighten me?

Best Answer

The operating system provides certain primitives for this kind of interprocess communication that don't require polling.

If process A is waiting on mutex M, the OS knows A can't be run and puts it aside in a bucket of processes waiting for something to happen. When the process holding M releases it, the OS looks at the list of processes waiting for it. The first process on the list, maybe A, gets removed from the idle bucket and put on the run queue. The next time A gets a time slice, the wait() it called will return and the program continues.