mutex_example.c

Download
c 41 lines 900 B
 1// mutex_example.c
 2// 뮤텍스를 이용한 동기화
 3#include <stdio.h>
 4#include <pthread.h>
 5
 6#define NUM_THREADS 10
 7#define ITERATIONS 100000
 8
 9int counter = 0;
10pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
11
12void* increment_safe(void* arg) {
13    (void)arg;
14
15    for (int i = 0; i < ITERATIONS; i++) {
16        pthread_mutex_lock(&mutex);    // 잠금
17        counter++;                      // 임계 구역
18        pthread_mutex_unlock(&mutex);  // 해제
19    }
20
21    return NULL;
22}
23
24int main(void) {
25    pthread_t threads[NUM_THREADS];
26
27    for (int i = 0; i < NUM_THREADS; i++) {
28        pthread_create(&threads[i], NULL, increment_safe, NULL);
29    }
30
31    for (int i = 0; i < NUM_THREADS; i++) {
32        pthread_join(threads[i], NULL);
33    }
34
35    printf("예상값: %d\n", NUM_THREADS * ITERATIONS);
36    printf("실제값: %d\n", counter);
37
38    pthread_mutex_destroy(&mutex);
39    return 0;
40}