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?
Threadpool in C++ is basically a pool having a fixed number of threads used when we want to work multiple tasks together (run multiple threads concurrently). This thread sits idle in the thread pool when there are no tasks and when a task arrives, it is sent to the thread pool and gets assigned to the thread.
A thread pool is a collection of worker threads that efficiently execute asynchronous callbacks on behalf of the application. The thread pool is primarily used to reduce the number of application threads and provide management of the worker threads.
The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable .
The size of a thread pool is the number of threads kept in reserve for executing tasks. It is usually a tunable parameter of the application, adjusted to optimize program performance. Deciding the optimal thread pool size is crucial to optimize performance.
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.
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