簡體   English   中英

提高線程池(C ++,pthreads)的性能

[英]Increase performance of thread pool (C++, pthreads)

我的應用程序有一個主線程,可將任務分配給多個工作線程。 通訊模式如下:

線程函數(這里的工作是一個函數指針):

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...*/
}

在主線程中(將任務分配給工作線程的函數):

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);

我在這里沒有使用隊列,因為一次只能有一個任務,並且主線程必須等待任務完成。 該模式工作正常,但性能較差。 問題在於,執行單個任務的速度非常快,而任務分配卻非常頻繁。 因此,線程將非常頻繁地掛起並等待該條件。 我想減少pthread_mutex_(un)lock,phread_cond_wait和pthread_barrier的調用次數,但是我不知道該怎么做。

一次只有一項任務。

您不需要安排。 您不需要線程。 您可以擺脫鎖定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM