Part 2 of 6 · 3 min read
Create and join
In plain words: A thread is started like a function call that does not wait for the answer. A manager who hands a task to a worker and goes on with other work is a fair picture. The manager later checks that the task is done. The analogy stops at one point: a manager can walk away from a task for good, but a thread must be either collected or marked as "detached" (section 4).
The call has this shape:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start)(void *), void *arg);
threadreceives the new thread's identifier, a value of typepthread_t.attrholds options such as the stack size;NULLmeans the defaults.startis the function the new thread runs. It takes onevoid *argument and returns avoid *.argis the single argument passed to that function.
The new thread starts at the beginning of start, and the thread that called pthread_create continues at the next line. The call pthread_join(thread, &result) waits until that thread has ended and stores the thread's return value in result. It plays the role that waitpid plays for processes (Level 1, page 3).
#include <stdio.h>
#include <pthread.h>
static void *hello(void *arg) {
int n = *(int *)arg;
printf("thread got %d\n", n);
return NULL;
}
int main(void) {
pthread_t t;
int value = 7;
int rc = pthread_create(&t, NULL, hello, &value);
if (rc != 0) { fprintf(stderr, "create failed: %d\n", rc); return 1; }
pthread_join(t, NULL);
printf("thread finished\n");
return 0;
}
thread got 7
thread finished
Without the join, main could return before the thread printed anything, and the thread would be cut off (section 5).
Notice how errors are reported. The pthread functions do not return -1 and set errno as ordinary system calls do (Level 0, page 2). They return 0 on success and an error number directly on failure. A test that sets a stack size of 1 byte, far below the minimum, printed returned 22 (Invalid argument), errno is still 0. The value 22 is EINVAL, and errno was not touched. So the test is if (rc != 0), and the message comes from strerror(rc), not from perror.
pthread_create and pthread_join
pthread_create starts a new thread in the calling process that runs a given function with one argument, and stores the new thread's identifier. pthread_join blocks the caller until a given thread has ended, then returns that thread's result value and releases the thread's resources.
Example: pthread_create(&t, NULL, work, &job) starts work(&job) in a new thread, and pthread_join(t, NULL) waits for it to finish.
Check yourself:
1. What are the four parameters of pthread_create?
2. How does pthread_create report an error?
3. Which call plays the part of waitpid for threads?