2015-11-08 238 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你可以为数组中存储的每个对象提供一个互斥体作为类成员。 –