[c언어] 스레드 간 데이터 공유 방법

C언어를 사용하여 멀티스레드 프로그램을 작성할 때, 스레드 간에 데이터를 효과적으로 공유하는 것은 중요한 과제입니다. 이번 블로그에서는 C언어를 사용하여 스레드 간에 데이터를 공유하는 여러 가지 방법에 대해 알아보겠습니다.

메모리 공유

가장 기본적인 스레드 간 데이터 공유 방법은 메모리 공유입니다. 이 방법은 모든 스레드가 동일한 메모리 공간에 접근하여 데이터를 공유하는 방식이며, 주의해야 할 점이 많습니다. 데이터 일관성과 동기화 문제에 대한 고려가 필요합니다.

#include <stdio.h>
#include <pthread.h>

int shared_data = 0;

void *thread_function(void *arg) {
    shared_data++;
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, thread_function, NULL);
    shared_data++;
    pthread_join(tid, NULL);
    printf("shared_data: %d\n", shared_data);
    return 0;
}

위의 예제에서는 shared_data를 공유하여 쓰레드에서 증가시키고, 메인 함수에서 증가시켜 최종 값을 출력하는 코드입니다.

뮤텍스 (mutex)

뮤텍스는 공유되는 자원에 동시 접근을 제어하기 위해 사용됩니다. 뮤텍스를 사용하여 상호배제를 구현함으로써 여러 스레드가 동시에 공유 데이터에 접근하는 것을 방지할 수 있습니다.

#include <stdio.h>
#include <pthread.h>

int shared_data = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void *thread_function(void *arg) {
    pthread_mutex_lock(&mutex);
    shared_data++;
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, thread_function, NULL);
    pthread_mutex_lock(&mutex);
    shared_data++;
    pthread_mutex_unlock(&mutex);
    pthread_join(tid, NULL);
    printf("shared_data: %d\n", shared_data);
    return 0;
}

세마포어 (semaphore)

세마포어는 뮤텍스와 유사하지만 동기화 및 상호배제 외에도 스레드 간의 시그널링에 사용됩니다. 세마포어를 사용하여 특정 수의 허용되는 동시 접근을 제어할 수 있습니다.

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

int shared_data = 0;
sem_t semaphore;

void *thread_function(void *arg) {
    sem_wait(&semaphore);
    shared_data++;
    sem_post(&semaphore);
    return NULL;
}

int main() {
    sem_init(&semaphore, 0, 1);
    pthread_t tid;
    pthread_create(&tid, NULL, thread_function, NULL);
    sem_wait(&semaphore);
    shared_data++;
    sem_post(&semaphore);
    pthread_join(tid, NULL);
    printf("shared_data: %d\n", shared_data);
    return 0;
}

결론

C언어에서 스레드 간 데이터를 공유하는 세 가지 주요한 방법에 대해 알아보았습니다. 메모리 공유, 뮤텍스, 그리고 세마포어는 각각 장단점이 있으므로 상황에 맞게 적절히 선택하여 사용해야 합니다. 공유된 자원에 대한 안전한 접근을 보장하기 위해 주의깊게 사용해야 합니다.

참고문헌: