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
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 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
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 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
is only for simplicity. Check the array_of_bools
to find out which threads have already finished.