Threadpool implementation: condition_variables vs. yield()

c++, condition-variable, multithreading, std, stl

Solution

if your threads in the thread pool are constantly fed with tasks and you need fast response time, then yield is what you want, but yield will burn cpu cycles no matter what the waiting thread is doing. if not, you can use the conditional approach, threads will sleep until a task is ready (note though, a conditional can wake a thread, even if no ready signal was sent), the response time might be slower, but you will not burn cpu cycles.

i would recommend the conditional approach, and if the reaction time is too slow, switch to yield.

Problem

I try to develop a threadpool in C++ and I wonder if it is better to yield() the thread in the main loop of the worker thread or to wait on a condition variable: ``` void worker_thread( void ) { // this is more or less pseudocode while( !done ) { if( task_available ) run_task(); else std::this_thread::yield(); } } ``` versus ``` void worker_thread( void ) { // this is more or less pseudocode std::unique_lock< std::mutex > lk( mutex_ ); while( !done ) { if( task_available ) run_task(); else condition_.wait( lk ); } } ``` Any ideas? Will there be any performance differences between both versions?

Original source