cs24-22fa pthread_create

Introduction to Computing Systems (Fall 2022)

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:

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.

See Also

pthread_join()