pthread_t指针作为pthread_create的参数

use*_*322 3 c pointers pthreads

pthread_create的第一个参数是pthread_t指针.在下面的hello程序中,如果第一个参数是指向pthread_t(pthread_t*)而不是pthread_t()的指针,pthread_t则程序结束于Segmentation fault...... 为什么?

我不记得看到pthread_t*作为第一个参数的声明类型pthread_create.
Butenhof的书" 用POSIX线程编程 "的第2章说:

要创建线程,必须声明类型为pthread_t[not pthread_t*] 的变量.

根据规范,第一个参数pthread_create是指向pthread_t,所以为什么分段错误?



分段故障

pthread_t* thr;
pthread_create(thr, NULL, &hello, NULL);
Run Code Online (Sandbox Code Playgroud)



运行好

pthread_t thr;
pthread_t* pntr = &thr;
pthread_create(pntr, NULL, &hello, NULL);
Run Code Online (Sandbox Code Playgroud)



你好程序:

#include <pthread.h>
#include <stdio.h>

void * 
hello(void *arg){
  printf("Hello\n");
  pthread_exit(NULL);
}

int 
main(int argc, char **argv){
  pthread_t thr = 1;
  pthread_create(&thr, NULL, &hello, NULL);



  pthread_join(thr, NULL);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

pthread_create原型:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
Run Code Online (Sandbox Code Playgroud)

sim*_*onc 7

pthread_t* thr;
pthread_create(thr, NULL, &hello, NULL);
Run Code Online (Sandbox Code Playgroud)

声明指向a pthread_t而不为其分配存储空间的指针.当你打电话时pthread_create,它会尝试写信*thr.这是一个未定义的位置,几乎肯定会失败.

pthread_t thr;
pthread_t* pntr = &thr;
pthread_create(pntr, NULL, &hello, NULL);
Run Code Online (Sandbox Code Playgroud)

因为你已经thr为a 声明存储(在堆栈上)而起作用了pthread_t.

请注意,第二个工作版本可以简化为您的hello程序中使用的版本

pthread_t thr;
pthread_create(&thr, NULL, &hello, NULL);
Run Code Online (Sandbox Code Playgroud)

... pthread_t在堆栈上声明一个然后将指针传递给它pthread_create.