반응형
C언어로 Multi thread 구조를 만들다보면 자연스럽게 사용하게 되는 mutex lock과 conditional variable에 관한 예제이다.
#include "sys/time.h" #include "sys/types.h" #include <sys/poll.h> #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #define ITER 30 int g_data[ITER]; pthread_cond_t cond[ITER]; pthread_mutex_t mutex[ITER]; void* producer(void *data){ int rc; int idx = 0; while (1) { int idx_mod = idx % ITER; rc = pthread_mutex_lock(&mutex[idx_mod]); g_data[idx_mod] = idx; #ifdef __STDOUT_PRINT__ printf("producer.data: %d\n", g_data[idx_mod]); fflush(NULL); #endif rc = pthread_cond_signal(&cond[idx_mod]); rc = pthread_mutex_unlock(&mutex[idx_mod]); poll(0, 0, 1); idx++; } } void* consumer(void *data){ int rc; int my_thr_idx = *(int *)data; printf("consumer thread idx: %d\n", my_thr_idx); while (1) { rc = pthread_mutex_lock(&mutex[my_thr_idx]); rc = pthread_cond_wait(&cond[my_thr_idx], &mutex[my_thr_idx]); #ifdef __STDOUT_PRINT__ printf("comsumer[%d].data: %d\n\n", my_thr_idx, g_data[my_thr_idx]); fflush(NULL); #endif rc = pthread_mutex_unlock(&mutex[my_thr_idx]); } } int main() { // // producer thread // pthread_t thr_id_prod; if (pthread_create(&thr_id_prod, NULL, producer, NULL) != 0) { printf("thread create error(%d, %s)\n", errno, strerror(errno)); return 0; } poll(0, 0, 1000); // // consumer thread // pthread_t thr_id_cons[ITER]; int new_idx[ITER]; for (int idx=0; idx<ITER; idx++) { new_idx[idx] = idx; pthread_mutex_init(&mutex[idx], NULL); pthread_cond_init(&cond[idx], NULL); if (pthread_create(&thr_id_cons[idx], NULL, consumer, (void *) &new_idx[idx]) != 0) { printf("thread create error(%d, %s)\n", errno, strerror(errno)); return 0; } } int status; for (int idx=0; idx<ITER; idx++) { pthread_join(thr_id_cons[idx], (void **)&status); } return 0; }
위와 같이 코드를 작성하고, gcc compiler로 실행 파일을 만든다.
$ gcc -D__STDOUT_PRINT__ main.c -o my_test_app $ ./my_test_app
'C language' 카테고리의 다른 글
[C 언어] localtime() 함수를 signal handler에서 사용시 문제점 (0) | 2025.01.21 |
---|---|
C 언어 - 가변인자 매크로 (로그 함수 매크로 예제) (0) | 2025.01.08 |
C 언어로 작성된 Binary 파일에 Build Date 추가하기 (0) | 2024.12.17 |
Linux에서 Coredump 파일 생성하도록 설정하기 (0) | 2024.12.10 |
gdb - 자주 사용하는 명령 옵션 (0) | 2024.12.10 |