How to close thread detach C++?

前端 未结 3 1097
遥遥无期
遥遥无期 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:46

    You can control the thread something like this:

    std::atomic_bool running = false; // set to stop thread
    std::atomic_bool closed = false; // set by thread to indicate it ended
    
    void detached_thread_function()
    {
        running = true;
    
        // acquire resources
    
        while(running)
        {
            std::cout << "running" << '\n';
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    
        // release resources
    
        // set after all resources released
        closed = true;
    }
    
    int main()
    {
        std::thread(detached_thread_function).detach();
    
        std::this_thread::sleep_for(std::chrono::seconds(3));
    
        std::cout << "stopping detached thread" << '\n';
    
        running = false; // stop thread
    
        while(!closed) // you could code a timeout here 
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        // or use a condition variable?
    
        std::cout << "end program" << '\n';
    }
    

    The thread is signaled to end its function and the thread sets a flag to let the main function know it is safe to exit.

    If you have multiple threads you can use an atomic counter to exit when it reaches zero.

提交回复
热议问题