【问题标题】:Does "thread_local" work for a naked thread?“thread_local”是否适用于裸线程?
【发布时间】:2017-02-15 00:26:15
【问题描述】:
#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

对象在线程开始时分配,在线程开始时释放 线程结束。每个线程都有自己的对象实例。仅有的 声明为 thread_local 的对象具有此存储持续时间。

我只是想知道:

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

换句话说:

C++标准保证A::~A()会在裸线程函数f完成后被调用吗?

【问题讨论】:

  • 这很难从 C++ 标准的角度来回答,因为 C++ 标准没有像您使用它的方式那样的“裸线程”概念。但当然 C++ 线程将以某种特定于平台的方式实现,如果您碰巧直接编写相同的实现代码,您最终可能会得到相同的行为。

标签: c++ multithreading c++11 posix standards


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2013-02-19
    • 2015-03-03
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多