Is the following code thread safe:
THREAD A
std::vector<std::string> myCopy;
with_locked_mutex(m) {
myCopy = sharedCopy;
}
myCopy.clear() etc. // -- a
THREAD B
while(1) {
// do things ...
with_locked_mutex(m) {
sharedCopy.push_back(a); // -- b
}
}
In other words, will the COW semantics of std::vector (and that of std::string also, I think) create a race condition between a and b? If so, is there something I can do to prevent it?
Assuming
with_locked_mutex(m) { something }somehow ensures that the mutex is acquired before the code block and released after, the two operations will run in mutual exclusion, so no, there won’t be an issue.And a
std::vectorcannot use copy-on-write anyway.