In multithreaded environment, let's say I am adding data to a vector(V0) which is shared among different threads. I synchronized the access to the vector using a mutex. At one point, once the vector reaches a certain threshold, I take another mutex and swap the vector with an empty vector(V1). Now V1 contains the shared data.
My understanding is that if I access V1 by taking second mutex only, then I should always see the correct original V0 contents(before swap). So I can synchronize V1 by using second mutex only.
Is this understanding correct?
std::vector<int> primary;
std::vector<int> secondary;
std::mutex p1;
std::mutex s1;
// called on thread1, thread2, thread3
void f1(int x) {
std::lock_guard l1{p1};
primary.push_back(x);
}
// could be called on thread1, thread2, thread3
void f2() {
std::lock_guard l1{p1};
std::lock_guard l2{s1};
std::swap(primary, secondary);
}
// called on thread4
void f3() {
std::lock_guard l2{s1};
std::copy(secondary.begin(), secondary.end(), std::ostream_iterator<int>(std::cout));
}
In the example above, f3() is always called last, my understanding is that the usage inside f3 is correct because we have synchronized access to secondary memory by using mutex1 and mutex2 in f2(). So we can use either of the two mutexes to access the secondary state.
Thanks, DDG