Pointer to boost::thread

后端 未结 1 1713
北海茫月
北海茫月 2021-01-26 19:19

I have a problem about the managed of thread.

My problem is that I want to create a class ThreadManager that have to manage all thread created and of course also destroy

相关标签:
1条回答
  • 2021-01-26 19:48
    void createThread(DerivedInterface& t)
    {
        boost::thread t1(&DerivedInterface::run, &t); 
        insert(&t1);
    }
    

    In the above t1 object gets created on the stack, then a pointer to t1 gets inserted into the map and then t1 goes out of scope and gets destroyed, so that all existing pointers to it become invalid.

    You can fix it by passing around shared_ptr<thread> instead of thread*:

    void insert(boost::shared_ptr<boost::thread>);
    void createThread(DerivedInterface& t)
    {
        boost::shared_ptr<boost::thread> t1(new boost::thread(&DerivedInterface::run, &t)); 
        insert(t1);
    }
    

    Or, by using r-value references in C++11:

    void insert(boost::thread&& t1);
    
    void createThread(DerivedInterface& t)
    {
        boost::thread t1(&DerivedInterface::run, &t); 
        insert(std::move(t1));
    }
    

    Alternatively, use boost::thread_group that does the above for you.

    0 讨论(0)
提交回复
热议问题