pthread_detach会为我管理我的记忆吗?

jbl*_*ers 3 c malloc multithreading memory-management pthreads

假设我有以下代码:

while(TRUE) {
  pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
  pthread_create(thread, NULL, someFunction, someArgument);
  pthread_detach(*thread);
  sleep(10);
}
Run Code Online (Sandbox Code Playgroud)

分离的线程是否会释放malloc分配的内存,还是我现在必须做的事情?

Com*_*ger 10

在pthread_create()无法知道的方式线程传递给它的指针是动态分配.pthreads不会在内部使用此值; 它只是将新的线程ID返回给调用者.您不需要动态分配该值; 你可以传递一个局部变量的地址:

pthread_t thread;
pthread_create(&thread, NULL, someFunction, someArgument);
Run Code Online (Sandbox Code Playgroud)