How to close thread detach C++?

前端 未结 3 1118
遥遥无期
遥遥无期 2021-01-03 17:20

I launched thread as detach. How to close thread from main function?

void My()
{
   // actions  
}


void main()
{

    std::thread thr7(receive);
    thr         


        
3条回答
  •  遥遥无期
    2021-01-03 17:45

    Short Answer:

    Use a shared variable to signal threads when to stop.

    Long answer:

    You cannot call join or terminate a thread directly from its parent once detach is called unless you use some other methods.

    Take a look at the following code (over simple and not very meaninful) which should show a simple way of doing what you are asking:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    std::mutex mu;
    std::condition_variable cv;
    bool finished = false;
    
    void threadFunc()
    {
        while(!finished)
        {
            
            std:: cout << "Thread doing work \n";
            std::this_thread::sleep_for(std::chrono::milliseconds(5));
        }
        
        std::cout << "End of Thread \n";
    }
    
    int main()
    {
    
        {
            std::thread t1(threadFunc);
            t1.detach(); // Call `detach` to prevent blocking this thread
    
        } // Need to call `join` or `detach` before `thread` goes out of scope
    
        for (int i = 0; i < 5; ++i){
            std::this_thread::sleep_for(std::chrono::milliseconds(20));
            std::cout << "Main doing stuff: \n";
        }
        std::cout << "Terminating the thread\n";
    
        std::unique_lock lock(mu);  
        finished = true;
        cv.notify_all();
        std::cout << "End of Main\n";
        return 0;
    }
    

    You use a shared variable to tell the threads when to terminate its execution.

提交回复
热议问题