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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <pthread.h>
#include <stdio.h>

void* worker(void* arg) {
    int *a_x = (int*)arg;
    while(*a_x < 100) {
        (*a_x)++;
    }
    printf("increment finished\n");
    return NULL;
}
int main() {
    int x = 0, y = 0;
    printf("x: %d, y: %d\n", x, y);

    pthread_t t1, t2;
    int status = pthread_create(&t1, NULL, worker, &x); // TODO: check if returns 0
    if(status != 0) {
        return EXIT_FAILURE;
    }
    // like calling worker(&x)

    /*
    // temporary:
    int num_threads = 2;
    pthread_t* threads = malloc(sizeof(*threads) * num_threads);
    pthread_create(&threads[0], NULL, worker, &y); // TODO: check if returns 0
    */

    pthread_create(&t2, NULL, worker, &y); // TODO: check if returns 0
    // like calling worker(&y)

    // Three threads are active now:  main thread, t1, and t2

    // Wait for t1 to finish, and then join (terminate the thread nicely)
    pthread_join(t1, NULL);

    // If t2 finished before t1 finished, then t2 is waiting now.
    pthread_join(t2, NULL);

    printf("x: %d, y: %d\n", x, y);
    return 0;
}

© Copyright 2016 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.