pthread_create(3)
的签名是:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
pthread_t *thread
参数的存储时长有什么要求? pthread_create
的手册页说:
Before returning, a successful call to
pthread_create()
stores the ID of the new thread in the buffer pointed to bythread
;
但不清楚它是否意味着它将值存储在那里以便调用者可以检查它,或者它是否使用该缓冲区来存储值(暗示缓冲区需要在子进程的整个生命周期内保持可用线)。
类似地,pthread_self
说它返回
the same value that is returned in
*thread
in thepthread_create(3)
call that created this thread.
但不清楚这是否意味着它返回 存储在 *thread
中的值或 等于 *thread 中返回的值
。
具体来说,我想知道这样的东西是否合法:
void make_thread(void) {
pthread_t tid;
return pthread_create(&tid, NULL, some_fn, NULL);
}
或者如果tid
需要malloc
。当我将 tid
放入堆栈时,我在 valgrind 中遇到了一堆与 _Unwind_ForcedUnwind
相关的错误,这让我怀疑 *thread
需要在子线程的生命周期内保持有效。
最佳答案
返回线程 ID 供您自己使用。如果您要分离线程或线程将自行分离,则不需要存储它。
void make_thread(void) {
pthread_t tid;
return pthread_create(&tid, NULL, some_fn, NULL);
}
这有点奇怪。你不能加入线程,因为你没有保留它的 ID。而你没有拆开它。我想如果线程自行分离,这可能没问题,但这是一种奇怪的做事方式。
关于c - `pthread_t*` 的 `pthread_create` 参数需要存活多长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928654/