https://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread.h.html
<pthread.h>
The header defines the following symbols: PTHREAD_CANCEL_ASYNCHRONOUS PTHREAD_CANCEL_ENABLE PTHREAD_CANCEL_DEFERRED PTHREAD_CANCEL_DISABLE PTHREAD_CANCELED PTHREAD_COND_INITIALIZER PTHREAD_CREATE_DETACHED PTHREAD_CREATE_JOINABLE PTHREAD_EXPLICIT_SCHED PTHR
pubs.opengroup.org
쓰레드로 병렬로 연산 수행 시, 뮤텍스를 통해 접근제어를 수행해 줄 필요가 있다.
#include <pthread.h>
#include <stdio.h>
#define endl "\n"
#define THREAD_COUNT 1000
int value = 0;
void *f(void *data) {
size_t idx = (size_t)data;
for (int i = 0; i < 10; i++) {
value++;
printf("i'm thread %zu, and value is %d now!" endl, idx, value);
}
return 0;
}
int main() {
pthread_t threads[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++)
pthread_create(threads + i, NULL, f, (void *)(size_t)i);
for (int i = 0; i < THREAD_COUNT; i++)
pthread_join(*(threads + i), NULL);
printf("now, the value is %d!" endl, value);
return 0;
}
위와 같이 락을 걸어주지 않으면, 아래와 같이 의도와 다른 값이 나오게 된다.

출력을 잘 보면, 숫자의 값이 도중에 줄어드는 것을 확인할 수 있다.
이는 아래와 같이 뮤텍스를 설정해서 해결해 줄 수 있다.
#include <pthread.h>
#include <stdio.h>
#define endl "\n"
#define THREAD_COUNT 1000
int value = 0;
pthread_mutex_t mutex;
void *f(void *data) {
size_t idx = (size_t)data;
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
value++;
printf("i'm thread %zu, and value is %d now!" endl, idx, value);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main() {
pthread_t threads[THREAD_COUNT];
if (pthread_mutex_init(&mutex, NULL)) {
printf("failed to init mutex!!");
return 1;
} //... or mutex = PTHREAD_MUTEX_INITIALIZER;
for (int i = 0; i < THREAD_COUNT; i++)
pthread_create(threads + i, NULL, f, (void *)(size_t)i);
for (int i = 0; i < THREAD_COUNT; i++)
pthread_join(*(threads + i), NULL);
printf("now, the value is %d!" endl, value);
return 0;
}

의도한 값이 나왔으며, 출력에서도 숫자가 일정하게 증가하는 것을 확인할 수 있다.
만약 뮤텍스를 동적 할당으로 생성하였을 경우, pthread_mutex_destroy를 호출해서 제거해주면 된다.
'C, C++' 카테고리의 다른 글
| C/C++] gcc 최적화 옵션 (0) | 2026.03.18 |
|---|---|
| C/C++] always_inline (0) | 2026.03.06 |
| C++] 템플릿 메타 프로그래밍 (0) | 2026.03.06 |
| C] spinlock (0) | 2026.03.05 |
| C] pthread 생성 및 활용 (0) | 2026.03.04 |