Multithreading 什么';锁定收藏的最佳方法是什么?

Multithreading 什么';锁定收藏的最佳方法是什么?,multithreading,concurrency,thread-safety,Multithreading,Concurrency,Thread Safety,假设我有一个通过多线程应用程序读写的项目集合。当涉及到对某些项应用算法时,我会使用不同的方法来获取锁 通过在整个操作过程中锁定: lock(collection) { for each thing in things { get the item from collection that matches thing do stuff with item } } 通过按需锁定: for each thing in things {

假设我有一个通过多线程应用程序读写的项目集合。当涉及到对某些项应用算法时,我会使用不同的方法来获取锁

通过在整个操作过程中锁定:

lock(collection)
{
    for each thing in things
    {
        get the item from collection that matches thing
        do stuff with item
    }
}
通过按需锁定:

for each thing in things
{
    lock(collection)
    {
        get the item from collection that matches thing
    }
    do stuff with item
}
或者通过按需锁定以获取要稍后处理的线程安全的项目集合,从而使集合锁定的时间更短:

Items items
for each thing in things
{
    lock(collection)
    {
        get the item from collection that matches thing
    }
    items.Add(item)
}
for each item in items
{
    do stuff with item
}

我知道这最终可能取决于应用于每个项目的实际算法,但您会怎么做?我使用C++,但我确信它是不相关的。< /P> < P>锁定获取和释放是昂贵的。我会锁定集合,而不是循环中的每个元素。如果整个操作需要是原子的,那么它是有意义的。

看看这个模式,它涉及到集合的单独字段/锁下的字段

同样值得一看的是,这种技术允许在其他线程更新集合时进行读取

编辑:
正如David Heffernan所提到的,在多线程环境中,通过线程读写来查看讨论

,您的第一个和第二个示例具有不同的含义。如果“DosomethingItem”与其他线程交互,则第三个示例可能还有另一个含义


在决定如何执行之前,您需要决定您希望代码执行的操作。

无论采用何种技术,在我的情况下您会怎么做?请参阅更新的答案,想法是在集合中引入单独的字段/变量,并锁定此特定字段,而不是锁定集合或每个元素(前者是一团糟!)在没有讨论“double checked locking is Breaked”声明的情况下,不要建议双重检查锁定。“do something with item”将与其他线程交互,但不会与使用我的项目集合的线程交互。