简体   繁体   English

隐含多线程,无锁列表的PLINQ问题/技术(在C#中)

[英]PLINQ problem / techniques to impliment multi-threaded, lock-free lists (in C#)

Here's the code in question: 这是有问题的代码:

             parentNodes.AsParallel().ForAll(parent =>
            {
                List<Piece> plist = parent.Field.GetValidOrientations(pieceQueue[parent.Level]);

                plist.ForEach(p =>
                {
                    TreeNode child = new TreeNode(p, parent);
                    var score = child.CalculateScore(root);
                    levelNodes.Add(child);
                });

            });

On runtime, that code occasionally leaves null references in levelNodes. 在运行时,该代码有时会在levelNodes中留下空引用。 I suspect this is due to thread lock, because the problem disappears if a normal (non-parallel) ForEach is called in place of the ForAll. 我怀疑这是由于线程锁定引起的,因为如果调用普通(非并行)ForEach代替ForAll,问题就会消失。

With the PLINQ implimentation, 'levelNodes.Add(child);' 带有PLINQ的含义是“ levelNodes.Add(child);” also occasionally throws an IndexOutOfRangeException with the message: "Source array was not long enough. Check srcIndex and length, and the array's lower bounds." 有时还会抛出带有消息的IndexOutOfRangeException:“源数组不够长。请检查srcIndex和length以及数组的下限。”

Any suggestions to eliminate this problem? 有什么建议可以消除这个问题?
Or perhaps performance would be increased with a lock-free List implimentation? 还是通过无锁List实现可以提高性能? (How might one go about this?) (怎么可能呢?)

Do you really need both levels of parallelism here? 在这里,您真的需要两个并行度吗? Is it not enough to just parallelise over the parent nodes? 仅在父节点上并行化还不够吗?

Anyway, writing to a List<T> from multiple threads without locking if definitely not a good idea. 无论如何,从多个线程写入List<T>而不锁定绝对不是一个好主意。 However, PFX comes with a concurrent collection which may fit your needs: ConcurrentBag . 但是,PFX附带了一个可以满足您需求的并发集合: ConcurrentBag It's unordered (to allow it to be lock-free) but given the interplay between threads here, I guess that's not an issue for you. 它是无序的(允许它是无锁的),但是考虑到这里线程之间的相互作用,我想这对您来说不是问题。

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

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