隐含多线程,无锁列表的PLINQ问题/技术(在C#中) [英] PLINQ problem / techniques to impliment multi-threaded, lock-free lists (in C#)

查看:93
本文介绍了隐含多线程,无锁列表的PLINQ问题/技术(在C#中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有问题的代码:

             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);
                });

            });

在运行时,该代码偶尔会在levelNodes中留下空引用.我怀疑这是由于线程锁定引起的,因为如果调用普通(非并行)ForEach代替ForAll,问题就会消失.

On runtime, that code occasionally leaves null references in 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.

具有PLINQ的含义,"levelNodes.Add(child);"有时还会抛出带有消息的IndexOutOfRangeException:源数组不够长.请检查srcIndex和length以及数组的下限."

With the PLINQ implimentation, '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."

是否有消除此问题的建议?
还是通过无锁List实现可以提高性能? (怎么可能呢?)

Any suggestions to eliminate this problem?
Or perhaps performance would be increased with a lock-free List implimentation? (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?

无论如何,从多个线程写入List<T>而不锁定绝对不是一个好主意.但是,PFX附带了一个可以满足您需要的并发集合: ConcurrentBag .它是无序的(允许它无锁),但是鉴于这里线程之间的相互作用,我想这对您来说不是问题.

Anyway, writing to a List<T> from multiple threads without locking if definitely not a good idea. However, PFX comes with a concurrent collection which may fit your needs: 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.

这篇关于隐含多线程,无锁列表的PLINQ问题/技术(在C#中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆