c++ - 并发 STL it++ 和 *it 安全吗?

标签 c++ stl iterator thread-safety

给定一个在单个编写器线程中创建的双向迭代器 it,递增迭代器 it++ 或分配它是否安全 it = list.begin() 并同时让一个或多个读取器线程使用 *it 取消引用它?

PS:it++ 将通过首先检查 std::next(it) 来防止成为 list.end()

//
// initialization (writer thread)
//

std::list<int> list;

for(int i=0; i<1000; i++)
    list.push_back(i);

auto it = list.begin();

//    
// writer thread:
//

auto nextit = std::next(it);

if(nextit == list.end())
    nextit = list.begin();

*nextit = newval();

it = nextit;

//        
// reader thread(s)
//

auto & val = *it;
std::cout << val << std::endl;

最佳答案

如果两个线程使用相同的迭代器(它们共享变量)。在一个线程中读取它并在另一个线程中修改它是不安全的。如果每个线程都有自己的迭代器(不同的变量)并且集合没有被修改,这是可以的。您可以从不同的线程读取列表。但是,如果您对容器进行任何修改,就会陷入 UB。

关于c++ - 并发 STL it++ 和 *it 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48418490/

相关文章:

c++ - 为什么 std::binary_search 返回 bool?

c++ - C++ 中的 Iterator 不是一种指针吗?

iterator - 如何在切片上返回迭代器?

c++ - 在两个数据结构中持有相同的唯一指针

c++ - 有什么方法可以通过 Qt Designer 添加 QSystemTrayIcon

map 抛出错误中的c++自定义对象

c++ - 自定义 std::allocator_traits::construct

python - 为什么 str(reversed(...)) 不给我反转的字符串?

c++ - Qt QGraphicsScene items() 段错误

c++ - 在 vector<pair<string, int>> 上使用 std::sort 的段错误