我写了一个示例程序来说明我的问题 - 我不明白为什么 firstVersion()
工作正常,而 secondVersion()
给我错误: 在没有事件异常中止的情况下终止调用
。感谢您的回答!
这是代码:)
#include <thread>
#include <iostream>
#include <chrono>
using namespace std;
const int threadCount = 100;
int N = 1;
void f() {
N++;
}
void firstVersion() {
thread * t[threadCount];
for(int i = 0; i < threadCount; i++) {
thread * ti = new thread{f};
t[i] = ti;
}
for(int i = 0; i < threadCount; i++) {
t[i]->join();
delete t[i];
}
}
void secondVersion() {
thread * t[threadCount];
for(int i = 0; i < threadCount; i++) {
thread ti{f};
t[i] = &ti;
}
for(int i = 0; i < threadCount; i++)
t[i]->join();
}
int main() {
//firstVersion();
secondVersion();
return 0;
}
最佳答案
第二个版本失败是因为线程的生命周期在调用 join()
之前的 for 循环结束时结束。
void secondVersion() {
thread * t[threadCount];
for(int i = 0; i < threadCount; i++) {
thread ti{f}; // local object of thread
t[i] = &ti;
} // the object dies without a join()
你的例子可以简化为:
void SomeFunc() {}
int main()
{
std::thread* tp;
//{
std::thread t{SomeFunc};
tp= &t;
//} // if the closing brace is present, object t calls destructor here!
tp->join();
}
如果查看您的 STL,您会发现以下代码:
~thread()
{
if (joinable())
std::terminate();
}
这只会导致调用 terminate
。
所以示例代码有两个错误:
1) 创建一个指向对象的指针,该对象在使用指针之前就已死亡,称为悬挂引用
2) 因为线程对象在 join() 被调用之前就死了,所以它简单地调用了终止。
关于c++ - 线程的静态与动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829899/