在Parallel.For中,是否可以同步每个线程?

时间:2014-05-21 12:17:21

标签: c# synchronization parallel.for

在Parallel.For中,是否可以将每个线程与' WaitAll'同步。 ?

  Parallel.For(0, maxIter, i =>
  {
            // Do stuffs

           // Synchronisation : wait for all threads => ???

           // Do another stuffs
  });

2 个答案:

答案 0 :(得分:5)

Parallel.For,在后台,将循环的迭代批处理为一个或多个Tasks,它可以并行执行。除非您获得分区的所有权,否则任务(和线程)的数量(并且应该!)将被抽象掉。只有完成所有任务后,控制才会退出Parallel.For循环(即不需要WaitAll)。

当然,理念是每个循环迭代都是独立的,不需要同步。

如果紧密循环中需要同步,那么您没有正确隔离任务,或者意味着Amdahl's Law生效,并且无法通过并行化加速问题。

但是,对于聚合类型模式,您可能需要在完成每个任务后进行同步 - 使用overloadlocalInit / localFinally来执行此操作,例如:

// allTheStrings is a shared resource which isn't thread safe
var allTheStrings = new List<string>();
Parallel.For(         // for (
  0,                  // var i = 0;
  numberOfIterations, // i < numberOfIterations;
  () => new List<string> (), // localInit - Setup each task. List<string> --> localStrings
  (i, parallelLoopState, localStrings) =>
  {
     // The "tight" loop. If you need to synchronize here, there is no point 
     // using parallel at all
     localStrings.Add(i.ToString());
     return localStrings;
  },
  (localStrings) => // local Finally for each task.
  {
     // Synchronization needed here is needed - run once per task
     lock(allTheStrings)
     {
        allTheStrings.AddRange(localStrings);
     }
  });

在上面的示例中,您也可以将allTheStrings声明为

var allTheStrings = new ConcurrentBag<string>();

在这种情况下,我们不需要lock中的localFinally

答案 1 :(得分:0)

您不应该(出于其他用户声明的原因),但如果您愿意,可以使用Barrier。这可以用于使所有线程在X个参与者遇到屏障之前在某个点等待(阻塞),导致屏障继续并且线程解除阻塞。正如其他人所说,这种方法的缺点是死锁

相关问题