Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threadpool implementation: condition_variables vs. yield()

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?

like image 631
headmyshoulder Avatar asked Jul 12 '13 11:07

headmyshoulder


People also ask

What is Threadpool in C++?

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.

What is the purpose of a thread pool?

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.

What is condition variable in multithreading?

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 .

What is thread pool size?

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.


1 Answers

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.

like image 67
Tiemo Jung Avatar answered Oct 15 '22 17:10

Tiemo Jung