gpt4 book ai didi

c++ - 线程的静态与动态内存分配

转载 作者:行者123 更新时间:2023-11-27 22:48:11 24 4
gpt4 key购买 nike

我写了一个示例程序来说明我的问题 - 我不明白为什么 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com