`pthread_create` 的 `pthread_t*` 参数需要存活多长时间?
How long does the `pthread_t*` argument to `pthread_create` need to survive?
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 by thread
;
但不清楚这是否意味着它将值存储在那里以便调用者可以检查它,或者它是否使用该缓冲区来存储值(暗示缓冲区需要在整个生命周期内保持可用子线程)。
同样,pthread_self
说的是returns
the same value that is returned in *thread
in the pthread_create(3)
call that created this thread.
但不清楚它是否意味着 returns 存储在 *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。而你没有拆开它。我想如果线程自行分离,这可能没问题,但这是一种奇怪的做事方式。
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
说的是returns
the same value that is returned in
*thread
in thepthread_create(3)
call that created this thread.
但不清楚它是否意味着 returns 存储在 *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。而你没有拆开它。我想如果线程自行分离,这可能没问题,但这是一种奇怪的做事方式。