c - `pthread_t*` 的 `pthread_create` 参数需要存活多长时间?

标签 c multithreading pthreads lifetime

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 说它返回

the same value that is returned in *thread in the pthread_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/

相关文章:

c - 如何从C中的完整路径获取文件的目录

.net - 如何从子线程或另一个线程到达父线程?

objective-c - Objective C - 后台执行选择器并且分离新线程选择器?

c - 在 C 中将行(来自结构体)动态分配到文件中

c - 为什么我会得到此代码的错误输出(打印数组中的回文数)?

java - 线程 hibernate 直到收到另一个类的通知

c - 操作系统 : Multiple Threads Slowing Down Program (C)

c - 共享 pthread_cond_broadcast 卡在 futex_wait

c - 在C中使用数组打印特定值

c - 三元运算符的奇怪枚举行为