【问题标题】:Pthread Best way to wake a number of threadsPthread 唤醒多个线程的最佳方法
【发布时间】:2018-10-13 06:15:33
【问题描述】:

我想知道用循环一次唤醒多个线程的最佳方法是什么 我考虑过使用 pthread_cond 但我不需要互斥锁,因为我不等待资源

有 n 个线程:

start of thread
loop
action
wait
end of loop

然后主线程会注意到它们都开始工作。 是使用 pthread cond 和每个线程的互斥锁更好,还是每次任务完成时重新创建线程更好?

【问题讨论】:

  • 只创建一次线程应该是更好的选择,因为如果频繁创建和清理线程可能会影响整体性能
  • @Pras 所以对于这个解决方案,我需要为每个线程创建一个互斥锁,它只适用于条件?

标签: c multithreading pthreads conditional-statements mutex


【解决方案1】:

您确实可以为此使用条件变量。它的工作方式是您的条件超过了主线程设置的某个共享变量,以指示工作线程应该继续。您确实需要互斥锁,因为您确实拥有共享资源 - 主线程设置和工作线程读取的共享变量。

类似:

/* shared variables */
int run_iteration = -1;
pthread_mutex_t iteration_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t iteration_cond = PTHREAD_COND_INITIALIZER;

工作线程:

int current_iteration = 0;

while (... )
{
    /* Wait for main to signal start of current_iteration */
    pthread_mutex_lock(&iteration_lock);
    while (run_iteration < current_iteration)
        pthread_cond_wait(&iteration_cond, &iteration_lock);
    pthread_mutex_unlock(&iteration_lock);

    /* ... Execute current_iteration ... */

    current_iteration++;
}

主线程:

/* signal start of next iteration */
pthread_mutex_lock(&iteration_lock);
run_iteration++;
pthread_cond_broadcast(&iteration_cond);
pthread_mutex_unlock(&iteration_lock);

或者,如果您需要线程同步运行,则可以使用 pthread 屏障 (pthread_barrier_t)。

【讨论】:

  • 感谢您澄清变量的使用,我搜索了我也可以使用 sem_t 来做同样的事情。
猜你喜欢
  • 1970-01-01
  • 2014-05-15
  • 2022-11-03
  • 2013-06-04
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
相关资源
最近更新 更多