c++ - 从两个线程调用 std::deque 上的删除和push_back是否是线程安全的?

标签 c++ multithreading stl deque

这里有两个函数:

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); }

调用是线程安全的 foobar来自两个不同的线程?行为是否未定义?

最佳答案

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.

erasepush_back 都不是原子的,因此您将遇到数据竞争。

“Effective C++ Digital Collection”告诉我们,您对实现的期望是:

enter image description here

关于c++ - 从两个线程调用 std::deque 上的删除和push_back是否是线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48605780/

相关文章:

php - 将数据从 C++ exe 返回到 web

python - 用 pybind11 包装一个 C++ 分配的实例

java - 同步(this)和同步(其他对象)之间有什么区别

c++ - 帮助更正源代码,使用模板

C++ STL 内存分配器编译错误

C++ 多重集 : removing the last element

c++ - 容器适配器不支持迭代器

c++ - 调用 join() 后如何恢复线程?

c# - 由 ThreadPool 中的线程填充的 ObservableCollection

c++ - STL 中 "end"指针非常量的基本原理