sanjoyd
sanjoyd

Reputation: 3340

C++'s std::vector and thread safety

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?

Upvotes: 1

Views: 326

Answers (2)

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

AFAIK, std::vector doesn't have COW semantics. The assignment operator and copy constructor always copy every element.

Upvotes: 2

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234444

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::vector cannot use copy-on-write anyway.

Upvotes: 3

Related Questions