I wrote code to do some parallel operations on a vector, my goal is to protect a single cell of a vector so other cells can be accessed in parallel, so I tried to use a vector of mutex of the same size of the other vector
vector<int> myIntVec(n,0);
vector<mutex> mtxVec(n);
then the critical section, each thread executes this (goal is to mark seen cells)
for (i of something)
{
mtxVec[i].lock();
if (myIntVec[i] == 0 ){
myIntVec[i] ;
mtxVec[i].unlock();
}
else
mtxVec[i].unlock();
}
no other operations on these 2 vectors. but doing some tests, what i got is that myIntVec cells contain numbers greater than 1, when they should contain at least 1. What am I missing?
CodePudding user response:
In order you share this link https://codecollab.io/@proj/InternetDivisionTrucks# in comments. Seems that you try to protect vector<bool> visited(nn); by mutexes vector<mutex> vis_lock(nn);. As i know there is special implementation for std::vector<bool> in which bools stored packed https://en.cppreference.com/w/cpp/container/vector_bool. so when it accesses to i-th element near elements also will be touched and with concurrency it's explodes because of accessing in one byte of memory at the same time. try replace std::vector<bool> to std::vector<char> or std::vector<int>
