何时在C中释放动态分配的pthread_t指针?

时间:2014-07-10 20:59:03

标签: c pthreads

我有一个输入case语句的代码块。如果我遇到了正确的情况,我需要创建一个新线程并继续执行工作。可以多次调用此case语句,创建多个同时运行的线程。

因此,我认为我需要为它创建一个pthread_t *,malloc一些内存,然后调用pthread_create()。但是,我还需要释放pthread_t *吗?我不想创建内存泄漏。如果我需要释放它,我应该如何以及在哪里释放它?

例如:

case MY_CASE:
    ; 
    pthread_t* foo = (pthread_t*)malloc(sizeof(pthread_t));
    pthread_create(foo, NULL, SomeFunction, &SomeParameters);
   .
   .
   .
 later
   .
   .
   .
free(foo); // Should this be in the code? If so, where?
/* I need to ensure the main thread keeps running. So, I cannot use pthread_join() */

1 个答案:

答案 0 :(得分:1)

在致电pthread_join(*foo, &retval);后释放内存。

如果您想轮询所有线程以查看它们是否已完成,请保留一组打开的句柄并在其上调用pthread_tryjoin_np。然后调用free(并从数组中删除)指向已终止的线程的指针。

或者,您可以在线程上调用pthread_detach。这样更便携,如果你不关心你的线程是否已经终止,它将会很好用。在这种情况下, pthread_detach手册页说明了这一点:

  

可以使用pthread_attr_setdetachstate(3)在分离状态下创建新线程,以设置at {{{}}

的attr参数的分离属性

您可以完全跳过malloc