2015-11-08 240 views
0

我所擁有的是一個數組,我想在一個元素上放置一個鎖,以便其他元素不能改變它。使用鎖定數組的鎖定元素C++

一種方法來描述這更好的爲您展示:

Array A = new Array; 

Thread1() { 

    while(array hasn't been completely changed) { 
    grab lock for random element within the array 
    alter the elements to this array 
    free the lock for the element 
    } 
} 

Thread2() { 

    while(array hasn't been completely changed) { 
    grab lock for random element within the array 
    alter the elements to this array 
    free the lock for the element 
    } 
} 

的目標是有兩個線程執行操作的元素,但它鎖定所以沒有其他線程可以訪問它。

回答

0

同比可能希望使用一個mutex如下面的示例代碼:

#include <mutex> 
#include <thread> 

using namespace std; 


mutex mtx[12]; 
int A [12]; 

auto modArray = [&mtx, &A](int position){ 
    while(!mutex[i].try_lock()); 
    modifiyArrayAtIndex(A, i); 
    mtx[i].unlock(); 
}; 

thread t1(modArray, 5); 
thread t2(modArray, 5); 
thread t3(modArray, 6); 
thread t4(modArray, 6); 
t1.join(); 
t2.join(); 
t3.join(); 
t4.join(); 

只是互斥的同等大小的數組匹配您的陣列,鎖定與您可能要修改索引互斥。 t1和t2線程正在處理索引5數據,而t3和t4線程正在處理索引6數據。

一個互斥只是同步查看在您希望的線程之間的resourcers中,

而(!mtx.try_lock())

積極等待的部分不是表現最好的選擇,但將完成這項工作。

+0

雖然這隻使用一個單一的鎖,但我的目標是構建優良的顆粒鎖,所以我想爲每個數組索引鎖定一個鎖。 – QQCompi

+0

@QQCompi,然後只是做一個互斥數組配對數組索引,只是爲了知道,你會訪問相同的數組索引形式不止一個線程? – Netwave

+0

@QQCompi你可以爲數組中存儲的每個對象提供一個互斥體作爲類成員。 –