rwlock_example.c

Download
c 90 lines 1.9 KB
 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}