pthread_create 的第一个参数是一个 pthread_t 指针。在下面的hello 程序中,如果第一个参数是指向 pthread_t ( pthread_t*) 而不是pthread_t ( ) 的指针,pthread_t则程序以Segmentation fault...为什么结束?
我不记得看到pthread_t*. 的第一个参数的声明类型pthread_create。
Butenhof 的书Programming with POSIX Threads的第 2 章说:
要创建一个线程,您必须声明一个类型为
pthread_t[notpthread_t*] 的变量。
但是根据规范,第一个参数pthread_create是指向的指针pthread_t,那么为什么会出现分段错误呢?
分段故障
pthread_t* thr;
pthread_create(thr, NULL, &hello, NULL);
运行正常
pthread_t thr;
pthread_t* pntr = &thr;
pthread_create(pntr, NULL, &hello, NULL);
你好程序:
#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;
}
pthread_create 原型:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);