voltento
voltento

Reputation: 887

Detect thread end

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 redistribute it.

Upvotes: 2

Views: 367

Answers (2)

cshu
cshu

Reputation: 5954

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.

Upvotes: 0

voltento
voltento

Reputation: 887

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.

Upvotes: 1

Related Questions