【发布时间】:2021-12-28 06:55:49
【问题描述】:
在C++11中,我创建了100个线程,每个线程调用Test::PushFunc,添加局部静态变量index,插入到局部集合变量本地地图。
理论上,index存储在Initialized Data Segment Memory中,并在程序运行时由每个线程添加。 下面一行
assert(it == localMap.end());
是合理的,因为 index 插入到 localMap 中不会重复。
但实际上,程序在断言中是随机转储的。你能告诉我为什么吗?谢谢。
#include <set>
#include <iostream>
#include <thread>
class Test {
public:
std::set<std::string> localMap;
void PushFunc()
{
static uint64_t index = 0;
while (true) {
std::cout << "index : " << index << "\n";
++index;
const auto& s = std::to_string(index);
const auto& it = localMap.find(s);
assert(it == localMap.end()); //! coredump here
localMap.insert(s);
if (index > 20000000) {
break;
}
}
}
};
int main ()
{
std::vector<std::thread> processThreads;
for (int i = 0; i < 100; ++i) {
processThreads.emplace_back(
std::thread([]()
{
Test t;
t.PushFunc();
}
));
}
for(auto& thread : processThreads){
thread.join();
}
}
【问题讨论】:
-
为什么是
const auto&? -
@ÖöTiib
localMap不在线程之间共享,只有index是。 -
为什么不能
const auto&?每个变量都不会改变可以定义为const
标签: c++ multithreading static-variables