簡體   English   中英

鎖定收藏集的通常最佳方法是什么?

[英]What's the usual best way to lock a collection?

假設我有一個在多線程應用程序中讀寫的項目集合。 在某些項目上應用算法時,我會采用不同的方式來獲取鎖。

通過在整個操作過程中鎖定:

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 ++,但是我很確定它是無關緊要的。

看一看Double Check鎖定模式,該模式涉及鎖定下集合/字段的單獨字段。

同樣值得一看的是Readers-writer鎖定技術,該技術可以在其他線程更新集合的同時進行讀取

編輯:正如David Heffernan提到的,請看“雙重檢查鎖定已損壞”聲明討論

在多線程設置中,通過讀寫線程,您的第一個和第二個示例具有不同的含義。 如果“用項目做某事”與其他線程進行交互,則您的第三個示例可能還有另一種含義。

您需要先決定要執行的代碼,然后再決定如何做。

鎖的獲取和釋放很昂貴。 我會鎖定集合,而不是循環中的每個單獨元素。 如果整個操作需要是原子的,這是有道理的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM