假設我有一個多線程應用程序讀取和寫入的項目集合。當涉及到在一些項目上應用算法時,我會用不同的方法獲取鎖。通常鎖定集合的最佳方法是什麼?
通過在整個操作過程中鎖定:
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
不建議在沒有討論「雙重檢查鎖定已損壞」聲明。 –