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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With