【发布时间】:2009-04-21 18:02:26
【问题描述】:
#include <pthread.h>
static void * worker_thread(void *);
void some_func(void)
{
pthread_t * tmp;
tmp = malloc(sizeof(pthread_t));
if (NULL != tmp)
{
if (!pthread_create(tmp, NULL, worker_thread, (void *)tmp))
pthread_detach(*tmp);
else
free(tmp);
}
}
static void * worker_thread(void * p)
{
/* do work */
free(p);
return(NULL);
}
【问题讨论】:
-
我觉得你的冒犯很冒犯。
-
你有一个竞争条件。在实际使用它来分离线程之前,您最终可能会释放 tmp。为什么不直接使用堆栈变量?
-
当心人们可能会标记它
-
无论如何,代码看起来很可疑。我不认为这是正确的。虽然我缺乏 pthread 知识
-
@Jamie:内核会管理你的线程。如果你不需要它,你对标识符做什么并不重要(除非你释放它然后使用它:p)。此外,线程可以自行分离。调用 pthread_self() 从新线程中获取线程标识符。你经常看到:pthread_detach(pthread_self());
标签: linux multithreading posix pthreads