【发布时间】:2017-07-07 01:10:13
【问题描述】:
在共享的std::forward_list 中,如果多个线程保证永远不会使用相同的位置迭代器调用insert_after,它们是否安全?鉴于插入保证不会使其他迭代器无效,并且容器没有 size() 方法,这似乎是安全的,但也许我遗漏了什么?
编辑:
我写了一个小的酷刑测试程序,它似乎在 Clang 中运行良好,没有任何锁定:
#include <forward_list>
#include <iostream>
#include <thread>
#include <vector>
using List = std::forward_list< int >;
using It = List::const_iterator;
void insertAndBranch (List& list, It it, int depth)
{
if (depth-- > 0) {
It newIt = list.insert_after (it, depth);
std::thread thread0 ([&]{ insertAndBranch (list, it, depth); });
std::thread thread1 ([&]{ insertAndBranch (list, newIt, depth); });
thread0.join();
thread1.join();
}
}
int main()
{
List list;
insertAndBranch (list, list.before_begin(), 8);
std::vector< It > its;
for (It it = list.begin(); it != list.end(); ++it) {
its.push_back (it);
}
std::vector< std::thread > threads;
for (It it : its) {
threads.emplace_back ([&]{ list.insert_after (it, -1); });
}
for (std::thread& thread : threads) {
thread.join();
}
for (int i : list) {
std::cout << i << ' ';
}
std::cout << '\n';
}
我知道这并不能证明什么,但它让我希望这是安全的。不过,我不确定是否可以在没有标准确认的情况下使用它。
【问题讨论】:
-
副本是旧的,事情已经改变了。
-
好吧,OP 没有指定 C++ 标准..
-
C++14,我刚刚加了一个标签。
-
任何时候你有多个线程并且其中一个或多个是共享变量的写入者,那么你需要同步。如果没有,你有一个未定义行为的数据竞争。
标签: c++ multithreading thread-safety c++14 forward-list