The first argument of pthread_create is a pthread_t pointer. In the hello program below, if the first argument is a pointer to pthread_t (pthread_t*
) instead of a pthread_t (pthread_t
) the program ends with Segmentation fault
...why?
I don't remember seeing pthread_t*
as the declared type of the first argument of pthread_create
.
And chapter 2 of Butenhof's book Programming with POSIX Threads says:
To create a thread, you must declare a variable of type
pthread_t
[notpthread_t*
].
But according to the specification the first argument of pthread_create
is a pointer to pthread_t
, so why the segmentation fault?
Segmentation fault
pthread_t* thr;
pthread_create(thr, NULL, &hello, NULL);
Runs OK
pthread_t thr;
pthread_t* pntr = &thr;
pthread_create(pntr, NULL, &hello, NULL);
hello program:
#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 prototype:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);