Name
pthread_create
- create a new thread
Synopsis
#include <pthread.h>
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void *),
void *restrict arg);
Description
The pthread_create()
function starts a new thread in the calling process. The new thread starts execution by invoking start_routine()
; arg
is passed as the sole argument of start_routine()
.
The new thread terminates in one of the following ways:
- It returns from
start_routine()
. This is equivalent to callingpthread_exit(3)
with the value supplied in the return statement. - Any of the threads in the process calls
exit(3)
, or the main thread performs a return from main(). This causes the termination of all threads in the process. - It calls
pthread_exit(3)
, specifying an exit status value that is available to another thread in the same process that callspthread_join(3)
. - It is canceled (look up
pthread_cancel(3)
).
The attr
argument points to a pthread_attr_t
structure whose contents are used at thread creation time to determine attributes for the new thread. If attr
is NULL
, then the thread is created with default attributes.
Before returning, a successful call to pthread_create()
stores the ID of the new thread in the buffer pointed to by thread
; this identifier is used to refer to the thread in subsequent calls to other pthreads functions.
Example
#include <pthread.h>
void *child(void *arg) {
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t p[10];
for (size_t i = 0; i < 10; i++) {
pthread_create(&p[i], NULL, child, NULL);
}
for (size_t i = 0; i < 10; i++) {
pthread_join(p[i], NULL);
}
return 0;
}
Return Value
On success, pthread_create()
returns 0
; on error, it returns an error number, and the contents of *thread
are undefined.