Check if thread is a boost thread

前端 未结 3 1828
野趣味
野趣味 2021-01-19 06:55

For purposes of thread local cleanup I need to create an assertion that checks if the current thread was created via boost::thread. How can I can check if this was the case

3条回答
  •  盖世英雄少女心
    2021-01-19 07:32

    Each time a boost thread ends, all the Thread Specific Data gets cleaned. TSD is a pointer, calling delete p* at destruction/reset.

    Optionally, instead of delete p*, a cleanup handler can get called for each item. That handler is specified on the TLS constructor, and you can use the cleanup function to do the one time cleaning.

    #include 
    #include 
    #include 
    
    void cleanup(int* _ignored) {
        std::cout << "TLS cleanup" << std::endl;
    }
    
    void thread_func() {
        boost::thread_specific_ptr x(cleanup);
        x.reset((int*)1); // Force cleanup to be called on this thread
    
        std::cout << "Thread begin" << std::endl;
    }
    
    int main(int argc, char** argv) {
        boost::thread::thread t(thread_func);
    
        t.join();
    
        return 0;
    }
    

提交回复
热议问题