CodeBlanks Logo Icon CodeBlanks

pthread_create

Learn to create threads with pthread_create.

pthread_create

pthread_create creates a new thread. It takes four parameters: thread ID, attributes, start function and the argument to pass to the function.

The function signature must be void *(*start)(void *); it takes void * and returns void *. For example, pthread_create(&tid, NULL, worker, &value) runs worker in a new thread. NULL attributes use defaults. The thread starts running as soon as it is created.

Thread lifecycle

When a thread is created it starts running and lives until its function returns. When the function returns, the thread ends.

To wait for its end you use pthread_join(tid, NULL). It waits until the thread returns and releases resources. Calling join for every created thread is a good habit; you will see the details in the next lesson. The thread shares memory with the parent thread.

Practice Create and join a thread

Write void *worker(void *arg) with int *value = (int *)arg; *value = 42;. Declare int value = 0;. Call pthread_create(&tid, NULL, worker, &value); and pthread_join(tid, NULL);. Print with printf("value=%d\n", value);.

Starter code

main.c
#include <stdio.h>
#include <pthread.h>

// Write worker function
// Create with pthread_create
// Join and print

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <pthread.h>

void *worker(void *arg) {
    int *value = (int *)arg;
    *value = 42;
    return NULL;
}

int main(void) {
    pthread_t tid;
    int value = 0;
    pthread_create(&tid, NULL, worker, &value);
    pthread_join(tid, NULL);
    printf("value=%d\n", value);
    return 0;
}

Expected output

value=42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the third parameter of pthread_create?

  • Attributes
  • The thread ID
  • The start function Correct answer
  • The return value

Explanation: The third parameter is the start function.

2 Thread creation

Question
pthread_create(&tid, NULL, ____, &value);
Answer
pthread_create(&tid, NULL, worker, &value);

Explanation: The worker function runs in the new thread.

3 Match pthread_create parts

Term Meaning
pthread_create Starts thread
pthread_join Waits for end
NULL Default attributes
void * Argument and return type

All lessons in Advanced