condition_basic.c

Download
c 67 lines 1.5 KB
 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}