race_condition.c

Download
c 44 lines 1019 B
 1// race_condition.c
 2// 경쟁 쑰건 (Race Condition) μ‹œμ—°
 3#include <stdio.h>
 4#include <pthread.h>
 5
 6#define NUM_THREADS 10
 7#define ITERATIONS 100000
 8
 9// 곡유 λ³€μˆ˜
10int counter = 0;
11
12void* increment(void* arg) {
13    (void)arg;
14
15    for (int i = 0; i < ITERATIONS; i++) {
16        counter++;  // μ›μžμ μ΄μ§€ μ•ŠμŒ!
17        // μ‹€μ œλ‘œλŠ”: temp = counter; temp = temp + 1; counter = temp;
18    }
19
20    return NULL;
21}
22
23int main(void) {
24    pthread_t threads[NUM_THREADS];
25
26    // μŠ€λ ˆλ“œ 생성
27    for (int i = 0; i < NUM_THREADS; i++) {
28        pthread_create(&threads[i], NULL, increment, NULL);
29    }
30
31    // λŒ€κΈ°
32    for (int i = 0; i < NUM_THREADS; i++) {
33        pthread_join(threads[i], NULL);
34    }
35
36    // μ˜ˆμƒ: NUM_THREADS * ITERATIONS = 1,000,000
37    // μ‹€μ œ: 그보닀 적은 κ°’ (경쟁 쑰건으둜 μΈν•œ 손싀)
38    printf("μ˜ˆμƒκ°’: %d\n", NUM_THREADS * ITERATIONS);
39    printf("μ‹€μ œκ°’: %d\n", counter);
40    printf("손싀: %d\n", NUM_THREADS * ITERATIONS - counter);
41
42    return 0;
43}