0

我的第一个想法是关于Lock Will 在我测试SpinLockConcurrent Collections 在这里工作,但它更贵!

这里的过程基于并行编程。并且该任务正在并行运行多个。

在 SpinLock 版本期间,我有时会随机遇到一个错误,类似于"Index out of range".

我写的 SpinLock 版本无法完成我想要的工作,可以对其进行任何更改以使其正常工作吗?或者它不是为与这种情况完全相关而构建的吗?

任何信息?

它有更好的选择吗?

这就是我所做的:

     lock (lckRelatz)
     {
         relatz.Add(st);
     }

这是 SpinLock 版本 - 这是在并行运行的方法中:

        SpinLock spinLk = new SpinLock();
        bool gotLock = false;
        try
        {
            spinLk.Enter(ref gotLock);
            relatz.Add(st);
        }
        finally
        {
            if (gotLock)
                spinLk.Exit();
        }
4

1 回答 1

2

It seems like you are creating new SpinLock for each thread. That will not actually lock anything. You need to have one SpinLock and use that from all of your threads.

But using a concurrent collection is even better solution. They are highly optimized and using them means you don't have to worry about all the locking yourself.

于 2012-07-11T08:01:25.533 回答