【问题标题】:count how many times the threads running?计算线程运行了多少次?
【发布时间】:2015-11-19 02:49:57
【问题描述】:

例如,使用pthread_create创建两个线程,两个线程都打印“hello world”,我的问题是如何计算每个线程打印了多少次“hello world”?

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    我的问题是如何计算“hello world”打印了多​​少次 每个线程?

    最简单的方法是在文件顶部声明一个全局原子计数器:

    static std::atomic<int> counter = 0;
    

    然后让每个线程在每次打印“hello world”时递增计数器(即 ++counter)。然后在你的 main() 中,所有线程都加入后,你可以打印出值计数器。

    【讨论】:

      【解决方案2】:

      我可以向你展示子线程将变量传递给主线程的代码;

      void * thread_func(void *arg)
      {
          int num = 10; //assume 'num' is the times that child thread  printed "hello world"
          pthread_exit((void *)num);
      }
      
      int main()
      {
          pthread_t thread;
          void * tret;
          pthread_create(&thread,NULL,thread_func,NULL);
          pthread_join(thread,&tret);
          printf("%d\n",(int)tret);  
          return 0;
      }
      

      【讨论】:

      • pthread_exit((void *)num); - 这似乎有问题,因为它将一个 int 转换为一个指针,即使它正在做正确的事情,并返回 (void *)&num,它也会返回一个指向局部变量的指针,该指针在函数返回。
      • ....是的,num的类型有问题。num的类型应该是long,但是其他代码是正确的。你应该返回(void *)num ,不是(void *)&amp;num。如果你返回(void *)&amp;num,这将返回一个指向局部变量的porter。
      • 可以使用std::intptr_t 或std::uintptr_t(但我相信它可以正常工作)。也可以只是return (void*)num; BTW / 使用pthread_exit 是可选的,如果您将 pthreads 移至例如,则需要额外的移植工作。 std::thread 等人。
      • 不管整数类型如何,从任意整数转换为 void* 都是不好的形式,因为它不可移植。在某些平台上,仅使用某些整数值进行强制转换会导致未定义的行为。
      • @MarkBessey:有没有支持这种担忧的参考资料?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      相关资源
      最近更新 更多