Skip to content

项目中的测试程序子线程 detach() 之后,主线程退出抛了一个异常。分析过后发现是 zmq_context 退出时子线程中的 zmq_socket 没有释放导致的。复现如下:

cpp
/*******************************************************************************
 * @copyright Copyright (c) 2024
 *
 * @author Wu Wei
 * @version 0.1
 * @date 2024-03-11, created.
 *
 * @file thread_local.cpp
 * @brief 测试 thread 局部变量的销毁时机
 ******************************************************************************/

#include <iostream>
#include <thread>

class ThreadLocal
{
public:
    ThreadLocal() { std::cout << "Construct!" << std::endl; }

    ~ThreadLocal() { std::cout << "Destruct!" << std::endl; }
};

int main()
{
    std::cout << "Main thread. " << std::endl;

    std::thread th([]() {
        ThreadLocal tl; // 线程局部变量
        std::this_thread::sleep_for(std::chrono::seconds(2));
        std::cout << "Sub thread exit. " << std::endl;
    });

    std::this_thread::sleep_for(std::chrono::seconds(1));
    th.detach();
    std::cout << "Main thread exit. " << std::endl;
    return 0;
}

输出:

image.png

  1. 全局变量在 main() 函数之前初始化;
  2. 主线程退出后子线程直接退出,tl 并未析构。

改为

cpp
th.join();

输出:

image.png

子线程退出前 tl 析构。

基于 VitePress 构建