summaryrefslogtreecommitdiff
path: root/targets/threads.c
blob: ab4d80d74cb413a787cdda7fc101ec97c72b5bbb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Two threads and a mutex: each adds its share to `total`, main joins them
// and prints it. What clone, futex and a thread's exit look like to a tracer.
#include <pthread.h>
#include <stdio.h>

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
long total;

__attribute__((noinline)) static void *work(void *arg) {
    for (long i = 0; i < 1000; i++) {
        pthread_mutex_lock(&lock);
        total += (long)arg;
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, work, (void *)1);
    pthread_create(&b, NULL, work, (void *)2);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("total = %ld\n", total);
    return 0;
}