Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does waiting on a condition variable load the CPU core?

Does waiting on a condition variable cause the loop to load the CPU core to 100% with instructions? This is how waiting on a cvar is usually done in C++:

void worker_thread()
{
    // Wait until ready turns true and the condition variable is notified
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{return ready;}); //<-- does this load the cpu?
    // Do something
}

I assume something like this is the underlying implementation:

while (1)
{
    lock mutex;
    if (condition) signal();
    unlock mutex;
}

This code would load the processor core it is running on to 100% because there is no Sleep().

What happens in reality?

like image 613
Timur Nuriyasov Avatar asked Jan 27 '17 17:01

Timur Nuriyasov


3 Answers

In my case (that's how I found your question) The problem was in not specifying -pthread for compiler and linker. Yes, everything compiles and links without that flag, but 100% CPU usage.

like image 150
socketpair Avatar answered Nov 19 '22 18:11

socketpair


In any of compilers and OSs I've used it doesn't. Usually, synchronization primitives' underlying operations are performed as kernel calls unless it is explicitly declared, and OS's kernel cares of how it is performed.  Even if it is not in the standard, I think it is there only to allow C++ standard-compliant compilers to exist on exotic architectures. Unless you're using something really rare and specific, you shouldn't care about it.

like image 1
Leontyev Georgiy Avatar answered Nov 19 '22 18:11

Leontyev Georgiy


In general, this logic revolves around the implementation of scheduler in OS.

The functionality of waiting and waking up of thread are done in cooperation with the scheduler of OS.

Generic/Simple design : In the mentioned scenario, wait shall cause the thread to sleep and hence the scheduler shall move the thread from running state(run queue) to waiting/blocked state(wait queue) unless a specific condition is met. So, normally in this scenario, there might not be CPU cycle consumption.

Once the condition is met, the semaphore will intimate the scheduler so that the scheduler can wake up the thread that was waiting for the condition and schedule it (That is, it shall move the thread from waiting/blocked state(wait queue) to running state(run queue) and schedule it).

like image 1
Karthik Balaguru Avatar answered Nov 19 '22 18:11

Karthik Balaguru