2

Here're two functions:

std::deque<int> q;

// Push lots of elements to q
xxxxx

void foo() {
  auto begin = q.cbegin();
  auto end = q.cend();
  q.erase(begin, end);
}
void bar(int x) { q.push_back(x); }

Is is thread-safe to call foo and bar from two different threads? Is the behavior undefined?

Jun Guo
  • 484
  • 1
  • 3
  • 14
  • 3
    No, it isn't thread safe, since neither of these operations is _atomic_. –  Feb 04 '18 at 07:28

3 Answers3

3

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.

Neither erase no push_back is atomic, so you will have a data race.

"Effective C++ Digital Collection" tells us that you all you can hope for from an implementation is:

enter image description here

Yola
  • 18,496
  • 11
  • 65
  • 106
2

No, it is not thread-safe to call erase() and push_back() on std::deque<> from two threads.

Sid S
  • 6,037
  • 2
  • 18
  • 24
0

No. It is not safe.

Neither erase() nor push_back() are atomic operations.

You need to synchronize access to the std::deque between the threads. The simplest solution would be a std::mutex.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70