1// condition_basic.c
2// ์กฐ๊ฑด ๋ณ์ (Condition Variable) ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
3#include <stdio.h>
4#include <pthread.h>
5#include <stdbool.h>
6#include <unistd.h>
7
8pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
9pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
10bool ready = false;
11
12void* waiter(void* arg) {
13 int id = *(int*)arg;
14
15 pthread_mutex_lock(&mutex);
16
17 while (!ready) { // ์กฐ๊ฑด์ด false์ธ ๋์ ๋๊ธฐ
18 printf("[๋๊ธฐ์ %d] ์กฐ๊ฑด ๋๊ธฐ ์ค...\n", id);
19 pthread_cond_wait(&cond, &mutex); // ๋๊ธฐ (๋ฎคํ
์ค ํด์ ๋จ)
20 }
21 // pthread_cond_wait์์ ๊นจ์ด๋๋ฉด ๋ฎคํ
์ค ๋ค์ ํ๋๋จ
22
23 printf("[๋๊ธฐ์ %d] ์กฐ๊ฑด ๋ง์กฑ! ์์
์์\n", id);
24
25 pthread_mutex_unlock(&mutex);
26 return NULL;
27}
28
29void* signaler(void* arg) {
30 (void)arg;
31
32 sleep(2); // 2์ด ๋๊ธฐ
33
34 pthread_mutex_lock(&mutex);
35 ready = true;
36 printf("[์ ํธ์] ์กฐ๊ฑด ์ค์ ์๋ฃ. ์ ํธ ์ ์ก!\n");
37 pthread_cond_broadcast(&cond); // ๋ชจ๋ ๋๊ธฐ์์๊ฒ ์ ํธ
38 pthread_mutex_unlock(&mutex);
39
40 return NULL;
41}
42
43int main(void) {
44 pthread_t waiters[3];
45 pthread_t sig;
46 int ids[] = {1, 2, 3};
47
48 // ๋๊ธฐ ์ค๋ ๋ ์์ฑ
49 for (int i = 0; i < 3; i++) {
50 pthread_create(&waiters[i], NULL, waiter, &ids[i]);
51 }
52
53 // ์ ํธ ์ค๋ ๋ ์์ฑ
54 pthread_create(&sig, NULL, signaler, NULL);
55
56 // ๋๊ธฐ
57 for (int i = 0; i < 3; i++) {
58 pthread_join(waiters[i], NULL);
59 }
60 pthread_join(sig, NULL);
61
62 pthread_mutex_destroy(&mutex);
63 pthread_cond_destroy(&cond);
64
65 return 0;
66}