~increscent/c-examples

c-examples/condition_vars/condition.c -rw-r--r-- 1.2 KiB
d08deaa3Robert Williams renamed condition variable example 1 year, 7 months ago
                                                                                
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Hint: make sure you compile with -lpthread

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

struct thread_arg {
    pthread_mutex_t mutex;
    pthread_cond_t ready;
    int is_ready;
    int val;
};

void *my_thread(void *arg) {
    struct thread_arg *a = (struct thread_arg *)arg;

    while (1) {
        pthread_mutex_lock(&a->mutex);

        while (!a->is_ready)
            pthread_cond_wait(&a->ready, &a->mutex);

        printf("Got it: %d!\n\tThread id % 10: %d\n", a->val, pthread_self() % 10);
        a->is_ready = 0;

        pthread_mutex_unlock(&a->mutex);
    }

    return NULL;
}

int main(int argc, char **argv) {
    pthread_t tid_1;
    pthread_t tid_2;

    struct thread_arg arg;
    pthread_mutex_init(&arg.mutex, NULL);
    pthread_cond_init(&arg.ready, NULL);
    arg.is_ready = 0;

    pthread_create(&tid_1, NULL, my_thread, &arg);
    pthread_create(&tid_2, NULL, my_thread, &arg);

    int i = 0;
    while (++i) {
        pthread_mutex_lock(&arg.mutex);

        arg.val = i;
        arg.is_ready = 1;
        pthread_cond_signal(&arg.ready);

        pthread_mutex_unlock(&arg.mutex);
        
        sleep(1);
    }

    pthread_join(tid_1, NULL);
    pthread_join(tid_2, NULL);

    return 0;
}