【问题标题】:Detect thread end检测线头
【发布时间】:2017-01-20 07:24:50
【问题描述】:

如何检测线程何时结束(以独立于平台的方式)? 我必须为每个线程存储对象的副本,并且我想知道何时可以处置或重新分配它。

【问题讨论】:

    标签: multithreading c++11


    【解决方案1】:

    可能是通过 RAII 和 local_thread 机制。我们创建了一个在析构函数中有用的类。

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

    接下来,我们创建local_thread 变量。可以是全局的,也可以是类字段(thread_local类字段是隐式静态的)。

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

    因此,每次线程结束时都会调用useFullWork。 我喜欢创建一个全局变量并仅在需要时对其进行初始化,这样可以避免开销。

    【讨论】:

      【解决方案2】:

      如果有多个线程,为了检测其中任何一个被结束,你需要:

      用于通知的共享condition_variable,用于锁定的共享mutex,以及用于所有线程条件的共享变量。

      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));
      }
      

      您可以使用 bool 或 vector&lt;bool&gt; 数组来检查哪些线程已结束。如果您不关心在当前线程“完全”完成后通知的时间,您可能更喜欢notify_all 而不是notify_all_at_thread_exit

      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 只是为了简单。检查array_of_bools 找出哪些线程已经完成。

      【讨论】:

        猜你喜欢
        • 2013-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-08
        • 2011-11-25
        • 2015-05-25
        • 2012-10-18
        • 2023-03-10
        相关资源
        最近更新 更多