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}