Reputation: 225
What I have is an array and I want to place a lock on one element so that the other element cannot alter it.
A way to describe this better is by showing you:
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
}
}
The goal is to have both threads perform operations to an element but locking it so no other thread can access it.
Upvotes: 1
Views: 4732
Reputation: 42698
Yoy may want to use a mutex as the following example code:
#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();
Just match your array with an equal size array of mutexes, locking the mutex corresponding to the index you may want to modify. The t1 and t2 threads are dealing with the index 5 data while the t3 and t4 threads are working on index 6 data.
A mutex just synchronize the acces to the resourcers you want between threads, the
while(!mtx.try_lock())
active waiting part is not the best performing option but will do the job.
Upvotes: 2