Detect thread end

后端 未结 2 1774
悲&欢浪女
悲&欢浪女 2020-12-21 15:39

How can I detect when a thread was ended (in a platform independent way)? I have to store copies of objects for every thread and I want to know when I can dispose or redistr

相关标签:
2条回答
  • 2020-12-21 15:56

    It's possibly via RAII and local_thread mechanism. We create a class that do usefull work in destructor.

    class ThreadEndNotifer
    {
    public:
        ~ThreadEndNotifer()
        {
            // Do usefull work
            useFullWork();
        }
    }
    

    Next, we create local_thread variable. It can be global or class feild(thread_local class field is implicit static).

    class Foo 
    {
    private:
        // Remember about initialization like static feild
        thread_local ThreadEndNotifer mNotifer; 
    }
    

    So, the useFullWork will be called every time when any thread are ending. I like to create one global variable and init it only if needed, in this way I avoid overhead.

    0 讨论(0)
  • 2020-12-21 15:58

    With multiple threads, in order to detect any one of them was ended, you need:

    A shared condition_variable for notification, a shared mutex to lock, and shared variables for conditions of all threads.

    void call_me_at_the_end_of_a_thread(int index_of_thread){
        std::unique_lock<std::mutex> l(the_global_mutex);
        array_of_bools[index_of_thread] = true;
        num_of_dead_threads++; // global integer only for the convenience of checking before wait
        std::notify_all_at_thread_exit(the_global_condition_variable, std::move(l));
    }
    

    You may use an array of bool or vector<bool> for checking which threads was ended. You may prefer notify_all to notify_all_at_thread_exit if you don't care about the timing of notifying after current thread has finished "completely".

    void call_me_to_detect_thread_was_ended(void){
        static int copy_of_num_of_dead_threads;
        std::unique_lock<std::mutex> l(the_global_mutex);
        while(num_of_dead_threads==copy_of_num_of_dead_threads)
            the_global_condition_variable.wait(l);
        std::cout<<num_of_dead_threads - copy_of_num_of_dead_threads<<" threads finished.\n";
        copy_of_num_of_dead_threads=num_of_dead_threads;
    }
    

    num_of_dead_threads is only for simplicity. Check the array_of_bools to find out which threads have already finished.

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