xref: /libuv/docs/code/locks/main.c (revision d59d6e6f)
1 #include <stdio.h>
2 #include <uv.h>
3 
4 uv_barrier_t blocker;
5 uv_rwlock_t numlock;
6 int shared_num;
7 
reader(void * n)8 void reader(void *n)
9 {
10     int num = *(int *)n;
11     int i;
12     for (i = 0; i < 20; i++) {
13         uv_rwlock_rdlock(&numlock);
14         printf("Reader %d: acquired lock\n", num);
15         printf("Reader %d: shared num = %d\n", num, shared_num);
16         uv_rwlock_rdunlock(&numlock);
17         printf("Reader %d: released lock\n", num);
18     }
19     uv_barrier_wait(&blocker);
20 }
21 
writer(void * n)22 void writer(void *n)
23 {
24     int num = *(int *)n;
25     int i;
26     for (i = 0; i < 20; i++) {
27         uv_rwlock_wrlock(&numlock);
28         printf("Writer %d: acquired lock\n", num);
29         shared_num++;
30         printf("Writer %d: incremented shared num = %d\n", num, shared_num);
31         uv_rwlock_wrunlock(&numlock);
32         printf("Writer %d: released lock\n", num);
33     }
34     uv_barrier_wait(&blocker);
35 }
36 
main()37 int main()
38 {
39     uv_barrier_init(&blocker, 4);
40 
41     shared_num = 0;
42     uv_rwlock_init(&numlock);
43 
44     uv_thread_t threads[3];
45 
46     int thread_nums[] = {1, 2, 1};
47     uv_thread_create(&threads[0], reader, &thread_nums[0]);
48     uv_thread_create(&threads[1], reader, &thread_nums[1]);
49 
50     uv_thread_create(&threads[2], writer, &thread_nums[2]);
51 
52     uv_barrier_wait(&blocker);
53     uv_barrier_destroy(&blocker);
54 
55     uv_rwlock_destroy(&numlock);
56     return 0;
57 }
58