gpt4 book ai didi

c++ - thread_local 对象的销毁

转载 作者:行者123 更新时间:2023-11-30 03:27:17 25 4
gpt4 key购买 nike

在问题Using QSqlQuery from multiple threads结果是线程存储解决了这个问题。

我制作了一个简单的演示代码,以绝对清楚 C++11 thread_local 说明符。下面的代码创建了两个线程,它们将 ThreadLocal 对象作为本地唯一对象。 Storage::get 函数是线程特定的单例。标准是否保证在加入或退出线程函数时调用 ThreadLocal 析构函数?

使用 GCC 5.4.0 编译(g++ -o main main.cpp --std=c++11 -lpthread)

#include <thread>
#include <mutex>
#include <string>
#include <chrono>
#include <iostream>
#include <atomic>

static std::mutex mtx;

struct ThreadLocal {
std::string name;

~ThreadLocal() {
mtx.lock();
std::cout << "destroy " << name << std::endl;
mtx.unlock();
}
};

struct Storage {
static ThreadLocal &get() {
/* Thread local singleton */
static thread_local ThreadLocal l;
static std::atomic<int> cnt(0);
l.name = std::to_string(cnt);
cnt++;
return l;
}
};

void thread() {
mtx.lock();
std::cout << Storage::get().name << std::endl;
mtx.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main(int argc, const char **argv) {
std::thread t1(&thread);
std::thread t2(&thread);
t1.join();
t2.join();
}

最佳答案

如果对象被构建,它将在线程函数退出时销毁。几乎在 [basic.stc.thread]/2 上的那些确切的话:

A variable with thread storage duration shall be initialized before its first odr-use ([basic.def.odr]) and, if constructed, shall be destroyed on thread exit.

关于c++ - thread_local 对象的销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47498215/

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