Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Threading semaphore_wait vs while loop

Is there any difference between the following pieces of code 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;
}

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

OR

void *ManageSequencer(void *argument){
  SomeClass *someClass = (SomeClass *)argument;

  while (someClass->ThreadIsAlive()) {

    semaphore_wait(sem);

    //thread execution statements 

  }
  return argument;
}

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

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

like image 949
Aran Mulholland Avatar asked Jan 20 '11 08:01

Aran Mulholland


2 Answers

Yes, the first one will cause the processor much more work than the second. Basically, whenever the active thread in the first example gets scheduled, it will simply eat up all of its processor time spinning on that condition until the scheduler preempts it and gives another thread time. This means you have context switches and the thread's entire (potentially) time slice is used 100% every time and it actually does no work.

The second example will trap the thread in the kernel, so it won't get any processor time at all until the kernel gets the signal and resumes the thread. Once that happens, the scheduler will give it processing time again, but now we know it has actual work to do instead of just using its entire time slice pegging the CPU.

like image 104
Jason Coco Avatar answered Sep 30 '22 01:09

Jason Coco


A typical semaphore implementation will "park" the thread in the kernel so it's not using processor time. Strongly recommended for that reason :)

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

like image 23
Catfish_Man Avatar answered Sep 30 '22 02:09

Catfish_Man