简体   繁体   English

同步工作线程

[英]Synchronizing worker threads

I have a scenario for which I am trying to come up with the best synchronization approach. 我有一个方案,我试图提出最好的同步方法。 We assume that std::thread in C++11 is present, so no need to worry about differences between various threading libraries etc. 我们假设存在C ++ 11中的std :: thread,因此无需担心各种线程库之间的差异等。

The scenario is this. 情景是这样的。 Thread a, the main thread, wants to hand out tasks to a bunch of worker threads. 线程a,主线程,想要将任务分发给一堆工作线程。 Then, after giving out its final instruction for the time being, it needs to wait for all the threads to complete their work. 然后,在暂时发出最终指令后,需要等待所有线程完成其工作。 We don't want to join them, just wait for them to finish their given task. 我们不想加入他们,只是等待他们完成他们的任务。 Then thread a has to analyze the collected data from all threads, and then send out commands to the workers to begin the procedure again. 然后线程a必须分析来自所有线程的收集数据,然后向工作人员发送命令以再次开始该过程。

In short, these are the steps. 简而言之,这些是步骤。

  1. Thread a sends command x to all worker threads. 将发送命令x线程化到所有工作线程。
  2. Thread a waits until all the workers have finished. 线程一直等到所有工人都完成了。
  3. Thread a does processing. 线程a做处理。
  4. Go back to 1. 回到1。

What would you suggest that I use? 你会建议我用什么? Simple mutexes? 简单的互斥? Condition variables? 条件变量? A combination of the two? 两者的结合? Any tips on how to structure the synchronization to be as efficient as possible would be appreciated. 关于如何使同步结构尽可能高效的任何提示都将受到赞赏。

You have n worker threads and one main thread a , which delegates tasks to workers and must wait for them to complete these tasks before assigning them a new batch of tasks. 您有n个工作线程和一个主线程a ,它将任务委派给工作人员,并且必须等待他们完成这些任务,然后再为他们分配一批新任务。

The basic technique is to use a barrier (like boost::barrier ) to synchronize the end of the worker threads and a . 基本技术是使用屏障(如boost::barrier )来同步工作线程的结束和a

The barrier is inittialized at n+1 . 屏障在n+1处初始化。 Main thread a waits on the barrier, and each worker threads does the same at the end of its task. 主线程a等待的障碍,每个工作线程做同样的在其任务结束。 When the last thread called wait on the barrier, all the threads are woken up, and main thread can continue its work. 当最后一个线程在屏障上调用wait时,所有线程都被唤醒,主线程可以继续工作。 You may want to add a second barrier to block the worker threads until a new task is assigned to them. 您可能希望添加第二个屏障来阻止工作线程,直到为其分配新任务。

The body of worker thread may look like the following pseudocode: 工作线程的主体可能看起来像以下伪代码:

while (running) {
     startbarrier.wait(); // wait for main thread to signal start
     do_work();
     endbarrier.wait(); // signal end of work
 }

The same thing can also be implemented with semaphores. 使用信号量也可以实现相同的功能。 Both semaphore and barrier can be implemented with a mutex and a condition variable. 信号量和屏障都可以使用互斥锁和条件变量来实现。

See this SO question for more details. 有关详细信息,请参阅此SO问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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