CodeBlanks Logo Icon CodeBlanks

pthread_join

Learn to wait for threads with pthread_join.

pthread_join in detail

pthread_join(tid, &result) retrieves the value returned by the thread. If the function returned a pointer with return, that value is written to result.

The thread function returns void *. For example, return an int * with return r;, then in the parent use int *result; pthread_join(tid, (void **)&result);. You then access the value with *result. This is the standard way to get a thread's result back.

Detached threads

Sometimes you let a thread run independently without waiting. With pthread_detach(tid) you detach it; when it ends, resources are freed automatically.

A detached thread cannot be joined. A thread is either joined or detached; not both. Background logger or monitor threads are usually detached. The main flow does not care about them or wait for their end.

Practice Get the thread result

Write void *worker(void *arg) with int *r = malloc(sizeof(int)); *r = 99; return r;. Create with pthread_create(&tid, NULL, worker, NULL);. Retrieve with int *result; pthread_join(tid, (void **)&result);. Print with printf("result=%d\n", *result); and free(result);.

Starter code

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

// Write worker function (return value with malloc)
// Create and join to get result
// Print result

int main(void) {
    return 0;
}

Sample solution

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

void *worker(void *arg) {
    int *r = malloc(sizeof(int));
    *r = 99;
    return r;
}

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

Expected output

result=99

Questions and answers

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

1 Match join concepts

Term Meaning
pthread_join Gets return value
pthread_detach Makes independent
void ** Pointer to pointer
return Ends function

2 What does the second parameter of pthread_join take?

  • The thread ID
  • Attributes
  • Wait duration
  • Return value pointer Correct answer

Explanation: The second parameter is the pointer for the return value.

3 Get value with join

Question
pthread_join(tid, (void **)&____);
Answer
pthread_join(tid, (void **)&result);

Explanation: The return value is written to the result pointer.

All lessons in Advanced