Goodspeed

导航

Parallel的陷阱

var nums = Enumerable.Range(1,4).ToArray();
            int total = 0;
            Parallel.For<int>(
                fromInclusive: 0,
                toExclusive: nums.Length,
                /* 陷阱 */
                localInit: () => 1,
                body: (i, loopState, subtotal) =>
                {
                    return subtotal + nums[i];
                },
                localFinally: i => Interlocked.Add(ref total, i)
                );
            Console.WriteLine("total={0}",total);
localInit会根据启动的线程来调用多次。

如果只启用了一个线程,结果是11,二个是否2

posted on 2014-11-02 12:44  Goodspeed  阅读(365)  评论(0编辑  收藏  举报