首页 > 解决方案 > 如何使进程与随机数量的活动线程同步?

问题描述

我有以下问题。我的进程产生了 4 个线程,它们独立执行相同的任务,需要等待所有线程完成处理,然后再进行下一个处理迭代。但是,活动线程的数量,即处理数据的线程数,需要等待其他线程完成的数量在 1 到 4 之间是可变的。例如,有时 2 个线程将处理数据,它们需要相互等待在继续之前。

我已经读过障碍可以为我做到这一点,但是,当它们被创建时,我必须指定要等待的线程数,而我的应用程序并非如此。此外,由于应用程序的实现方式,每次都创建/销毁障碍会很尴尬和复杂。

我想知道是否有另一种方法可以解决这个问题。

谢谢!

标签: linuxmultithreadingsynchronizationsemaphorebarrier

解决方案


这就是使用 Semaphore 实现它的方法。

// Global Sempahore initialized to zero.
Sempahore global_sempahore(0)

// Your main thread which spawns your 'n' worker thraeds.
// After spawning 'n' threads your main thread will wait for those threads to finish.
for (int i=0; i<n; i++) {
    global_sempahore.sem_wait();
}


// This is your worker thread routine.
// After processing the common work routine before exiting each thread will signal the sempahore.
global_sempahore.sem_post();

这个想法是用 0 在锁定模式下初始化信号量。在主线程中生成n 个工作线程后,在信号量上等待n次。

在退出信号之前的工作线程中,信号量。

这将确保主线程只有在所有n 个线程完成执行时才会唤醒。


推荐阅读