There are a couple of things that I don't understand about the function pthread_create
.
here is the header
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void*),
void *restrict arg);
Firstly, I'm not familiar with the syntax of void *(*start_routine)(void*),
. I know that the argument asked for here is the name of a function that returns void *
, and takes one void *
as its argument. Presumably pthread_create
will refer to that funcion as start_routine
. So I suppose this argument would be a function pointer? If so, what are the key syntax elements that make it so?
Secondly, why does pthread_create
expect a function that has void *
as its return type? What would pthread_create
be able to do with data of unkown type?
The void *(*start_routine)(void*)
should be read in the following order:
start_routine
- Name of the argument. *start_routine
- So this argument is a pointer. (*start_routine)(...)
- Aha, it's a pointer to a function. (*start_routine)(void*)
- We now know the argument(s) of the function. void *(*start_routine)(void*)
- And finally, this tells us the return type of the function. The void*
argument receives whatever is passed to arg
- so if you need to pass any "input" to your new thread this is one way to do it.
The resulting void*
is used as thread's exit status (as alternative to calling pthread_exit()
explicitly). You can get this status through pthread_join()
.
void *(*start_routine)(void*)
is a function pointer. Everything about it is the 'key syntax', but in particular the syntax (*ptrname)(args)
.
pthreads doesn't do anything with the void* that the start routine returns except to return it to you. See the man page for pthread_join
to see how it comes back to you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.