简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM