gpt4 book ai didi

c++ - "thread_local"是否适用于裸线程?

转载 作者:搜寻专家 更新时间:2023-10-31 00:55:22 25 4
gpt4 key购买 nike

#include <pthread.h>
#include <thread>
#include <iostream>

using namespace std;

struct A
{
~A()
{
cout << "~A()" << endl;
}
};

void* f(void*)
{
thread_local A a;
return 0;
}

int main()
{
pthread_t tid;
pthread_create(&tid, nullptr, f, nullptr);
this_thread::sleep_for(5min);
}

根据 cppreference :

The object is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the object. Only objects declared thread_local have this storage duration.

我只是想知道:

C++ 编译器如何知道何时创建和退出裸线程(而不是 std::thread)?

换句话说:

C++标准是否保证A::~A()会在裸线程函数f结束后被调用?

最佳答案

C++ 标准没有说明调用 pthread_create 时或之后发生的情况。因此,如果您想了解这一点,则必须查看 C++ 标准以外的其他地方。不幸的是,POSIX 标准对 C++ 线程局部对象只字不提。所以 POSIX 标准也不会说什么。

这意味着除非特定编译器、平台或线程标准的文档说明了具体内容,否则无法保证在特定平台上发生的任何事情。

关于c++ - "thread_local"是否适用于裸线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42238713/

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