【问题标题】:pthread_create with local variable as parameterpthread_create 以局部变量为参数
【发布时间】:2013-09-04 13:38:59
【问题描述】:

以下方式使用pthread_create时会不会出错?

void myFunction(){
  thread_t myThread;
  pthread_create(&myThread,0,myRoutine,0);
}

我不确定使用局部变量myThread 是否会导致错误,因为当myFunction() 退出时它不再存在。

函数退出时myThread的内存还能在内核中使用吗?

我不需要存储在myThread 中的线程ID,所以我不想分配内存并再次释放它。

【问题讨论】:

    标签: c++ pthreads posix local-variables


    【解决方案1】:

    您不应该让线程“刚刚结束”,因为这肯定会导致问题。如果您希望线程刚刚获胜,您应该至少使用pthread_detach,此时线程完全“独立”,并且应该可以保留它。

    【讨论】:

      【解决方案2】:

      您还可以在创建线程属性时将 PTHREAD_CREATE_DETACHED 作为线程属性的一部分传递。这样,您以后不必担心加入线程。像这样的:

       pthread_t;
       int status;
       pthread_attr_t attr;
      
       status = pthread_attr_init(&attr);
       if (status != 0) {
           fprintf(stderr, "pthread_attr_init() failed [status: %d]\n", status);
           return 0;
       }
      
       status = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
       if (status != 0) {
           fprintf(stderr, "pthread_attr_setdetachstate() failed [status: %d]\n", status);
           return 0;
       }
      
       status = pthread_create(&t, &attr, myRoutine, 0);
      

      【讨论】:

        【解决方案3】:

        我在下面这样使用pthread_create会不会出错?

        是的:您现在无法在线程结束时加入线程。这是资源泄漏,类似于丢失指向已分配内存的唯一指针。

        如果你实在不想有控制地关闭它,那么你可以打电话给pthread_detach,让它负责整理自己的资源;那么你就可以放心地放弃线程句柄了。

        函数退出时myThread的内存还能在内核中使用吗?

        没有。 pthread_t 只是用于访问线程资源的句柄。它不管理这些资源,除非您需要访问它们,否则它不需要存在。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-24
          • 2011-02-14
          • 2022-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-02
          相关资源
          最近更新 更多