1

是否可以在 Parallel.For 循环中使用相同的函数委托,或者我是否在死锁中运行。

这意味着我想做这样的事情:

    public Execute(float[] input, Func<float, int, bool> WorkOnIt)
    {
        Parallel.For(0, input.GetLength(0), i =>
        {
            if(WorkOnit(input, i)
               ...
            ...
         });
    }

非常感谢!

4

2 回答 2

0

That depends on the details of WorkOnIt. Do you use any means of synchronization for externally visible objects that you have to be careful. If not then you are safe.

For example if your WorkOnIt looks like:

private void MyWorkOnIt(float[] input, int idx)
{
    lock(input) { /* ... */ } // possible deadlock scenario
}

This could deadlock if the code that calls Execute locks on the same object:

lock(myInput)
{
    Execute(myInput, MyWorkOnIt);
}

In general I would try to make the delegates of parallel loops completely independent of any shared state. If I can't do - e.g. when I have to aggregate items - then I'll use one of the parallel loops which use a local state.

于 2014-09-16T08:08:05.527 回答
0

您可以使用相同的函数,但请注意,如果您需要使用在函数范围之外声明的数据,则需要确保这些数据类型的线程安全,例如使用锁定。

http://msdn.microsoft.com/de-de/library/system.threading.tasks.parallel(v=vs.110).aspx

编辑:当然,如果您认为 smtg 是这样的,您当然可以使用并行任务生成死锁:

void myfunction(...) {
   lock (locker) {
       doSomethingWithAGlobalList(..);
       waitForOtherTasksDoingThingsWithThatList(..);
   }
}

但这不是您的 Parallel.For 问题,而是由进入 myfunction 的任何并发线程引起的

于 2014-09-16T07:59:58.090 回答