1// rwlock_example.c
2// ě˝ę¸°-ě°ę¸° ě ę¸ (Read-Write Lock) ěě
3#include <stdio.h>
4#include <stdlib.h>
5#include <pthread.h>
6#include <unistd.h>
7#include <time.h>
8
9#define NUM_READERS 5
10#define NUM_WRITERS 2
11
12// ęłľě ë°ě´í°
13typedef struct {
14 int data;
15 pthread_rwlock_t lock;
16} SharedData;
17
18SharedData shared = { .data = 0 };
19
20void* reader(void* arg) {
21 int id = *(int*)arg;
22
23 for (int i = 0; i < 5; i++) {
24 pthread_rwlock_rdlock(&shared.lock); // ě˝ę¸° ě ę¸
25
26 printf("[ë
ě %d] ë°ě´í° ě˝ě: %d\n", id, shared.data);
27 usleep(100000); // ě˝ę¸° ě¤...
28
29 pthread_rwlock_unlock(&shared.lock);
30
31 usleep(rand() % 200000);
32 }
33
34 return NULL;
35}
36
37void* writer(void* arg) {
38 int id = *(int*)arg;
39
40 for (int i = 0; i < 3; i++) {
41 pthread_rwlock_wrlock(&shared.lock); // ě°ę¸° ě ę¸ (ë°°íě )
42
43 shared.data = rand() % 1000;
44 printf("[ěę° %d] ë°ě´í° ě: %d\n", id, shared.data);
45 usleep(200000); // ě°ę¸° ě¤...
46
47 pthread_rwlock_unlock(&shared.lock);
48
49 usleep(rand() % 500000);
50 }
51
52 return NULL;
53}
54
55int main(void) {
56 srand(time(NULL));
57
58 pthread_rwlock_init(&shared.lock, NULL);
59
60 pthread_t readers[NUM_READERS];
61 pthread_t writers[NUM_WRITERS];
62 int reader_ids[NUM_READERS];
63 int writer_ids[NUM_WRITERS];
64
65 // ë
ě ěěą
66 for (int i = 0; i < NUM_READERS; i++) {
67 reader_ids[i] = i;
68 pthread_create(&readers[i], NULL, reader, &reader_ids[i]);
69 }
70
71 // ěę° ěěą
72 for (int i = 0; i < NUM_WRITERS; i++) {
73 writer_ids[i] = i;
74 pthread_create(&writers[i], NULL, writer, &writer_ids[i]);
75 }
76
77 // ë기
78 for (int i = 0; i < NUM_READERS; i++) {
79 pthread_join(readers[i], NULL);
80 }
81 for (int i = 0; i < NUM_WRITERS; i++) {
82 pthread_join(writers[i], NULL);
83 }
84
85 pthread_rwlock_destroy(&shared.lock);
86 printf("ěëŁ\n");
87
88 return 0;
89}