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

标签 c++ multithreading

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

相关文章:

java - 将数据插入二维 byte[] 数组

java - 在定义的时间段内通过 Wifi 发现设备

java - 为什么当我运行代码时 obj.start() 不运行?

c - 没有锁的一插入多读列表安全吗?

c++ - 何时声明类(class)成员

java - 调用 Thread.getAllStackTraces() 时发生挂起

C++ 无法从映射中调用 lambda 表达式

c++ - C++ 中 64 位整数的奇怪行为

Python 字典到 C++ 映射

c++ - 在 C++ 中, “throw” 和 “throw ex” 之间有区别吗?