简体   繁体   中英

Increase performance of thread pool (C++, pthreads)

My application has a main thread that assigns tasks to a number of worker threads. The communication pattern is the following:

The thread function (work is a function pointer here):

while(true) {
    pthread_mutex_lock(mutex);
    while(!work)
        pthread_cond_wait(cond, mutex); // wait for work...
    pthread_mutex_unlock(mutex);

    work();

    pthread_barrier_wait(barrier); /*all threads must finish their work*/
    if(thread_id == 0) {
        work = NULL;
        pthread_cond_signal(cond); /*tell the main thread that the work is done*/
    }
    pthread_barrier_wait(barrier); /* make sure that none of the other worker
                                   threads is already waiting on condition again...*/
}

In the main thread (the function that assigns a task to the worker threads):

pthread_mutex_lock(mutex);
work = func;
pthread_cond_broadcast(cond); // tell the worker threads to start...
while(work)
    pthread_cond_wait(cond, mutex); // ...and wait for them to finish
pthread_mutex_unlock(mutex);

I did not use a queue here, because there can only be one task at a time and the main thread has to wait for the task to finish. The pattern works fine, but with poor performance. The problem is that tasks will be assigned very often while performing a single task is quite fast. Therefore the threads will suspend and wait on the condition very often. I would like to reduce the number of calls of pthread_mutex_(un)lock, phread_cond_wait and pthread_barrier, but I do not see how this could be done.

There is only one task at a time.

You don't need scheduling. You don't need threads. You can get rid of the locking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM