Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while(true) vs wait+condition synchronism

Is it a bad practice to put a thread in a while(true) loop and test if a condition is ok to start a treatment?

void run()
{
    for(;;)
    {
        if(dataReady)
        {
            processData();
        }
    }
}

is it preferable to use wait/condition mechanism :

void run()
{
    for(;;)
    {
        if(dataReady)
        {
            processData();
        }
        lock_guard lock(mutex);
        condition_.wait(lock);
    }
}

Another thread of course calls condition_.notify_one()

EDIT:

I expect to almost never wait.

like image 294
Guillaume Paris Avatar asked Dec 09 '22 07:12

Guillaume Paris


2 Answers

while true is a bad way because it just eats processing cycles.
Second approach is better, where in the thread gets intimated only when it has to perform some work.

like image 66
Alok Save Avatar answered Dec 26 '22 00:12

Alok Save


It depends on the amount of time you expect to be waiting.

For very short periods a busy-wait can be preferable because it wouldn't involve a context switch as the other technique. The overhead of the context switch may sometimes overweigh the whole busy-wait loop.

like image 36
Blagovest Buyukliev Avatar answered Dec 26 '22 00:12

Blagovest Buyukliev