C: Threading semaphore_wait vs while loop

Is there a difference between the following code snippets in terms of processor usage?

void *ManageSequencer(void *argument){ SomeClass *someClass = (SomeClass *)argument; while (someClass->ThreadIsAlive()) { while(someClass->isAsleep) { } someClass->isAsleep = true; //thread execution statements } return argument; } 

when some class sets isAsleep=false periodically when it needs a thread to execute

OR

 void *ManageSequencer(void *argument){ SomeClass *someClass = (SomeClass *)argument; while (someClass->ThreadIsAlive()) { semaphore_wait(sem); //thread execution statements } return argument; } 

when someClass calls semaphore_signal(sem); periodically when it needs a thread to execute.

this question is not about atomicity, is it just that the while loop will cause the processor to work more than the semaphore solution. Does the semaphore only have a closed loop inside it that blocks until the condition is met (increment of the semaphore above zero)?

+4
source share
3 answers

Yes, the first one will make the processor work much better than the second. In principle, whenever the active thread in the first example receives the planned value, it simply absorbs the entire processor processing time in this state until the scheduler selects it and gives a different thread time. This means that you have context switches, and the entire thread (potentially) of the flow time is used 100% each time, and it actually does not work.

The second example will delay the thread in the kernel, so it will not receive any processor time until the kernel receives a signal and resumes the thread. As soon as this happens, the scheduler will give it processing time again, but now we know that it has the actual work, and not just the use of its entire time segment, binding the processor.

+3
source

A typical semaphore implementation will "park" the thread in the kernel so that it does not use processor time. Highly recommended for this reason :)

(similarly, most mutex implementations will do this, but spinlocks will not)

+2
source

Your first example will be busy rotating in the outer loop if someClass->isAsleep is false. that is, he will spend all the processor time doing nothing.

Your second example will sleep on a semaphore and not waste CPU time. That is, the first case is very, very bad, the second case is good.

+2
source

Source: https://habr.com/ru/post/1336286/


All Articles