假设我有一个多线程应用程序读取和写入的项目集合。当涉及到在一些项目上应用算法时,我会用不同的方法获取锁。通常锁定集合的最佳方法是什么?
通过在整个操作过程中锁定:
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++,但我非常确定它是无关紧要的。
无论这种技术,你会怎么做我的情况? –
查看更新后的答案,想法是将单独的字段/变量与集合一起引入,并锁定该集合或每个元素的锁定的特定字段(前者是一团糟!) – sll
不建议在没有讨论“双重检查锁定已损坏”声明。 –