[c언어] 스레드 간 통신

C언어에서 멀티스레드 프로그래밍은 스레드 간 효율적인 통신이 필수적입니다. 두 가지 주요 방법으로 공유 메모리메시지 전달이 있습니다.

공유 메모리를 이용한 통신

C언어에서는 pthread 라이브러리를 사용하여 스레드를 생성하고 관리할 수 있습니다. 공유 메모리를 이용하여 스레드 간 데이터를 공유할 수 있습니다. pthread 라이브러리를 사용하여 공유 메모리에 접근하고 조작할 수 있습니다.

#include <pthread.h>

int shared_data; // 공유 데이터

void *thread_function(void *arg) {
    // 공유 데이터에 접근하여 조작
    shared_data = 10;
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_create(&thread, NULL, thread_function, NULL);

    // 다른 스레드에서 조작한 데이터 사용
    printf("%d\n", shared_data);
    return 0;
}

메시지 전달을 통한 통신

C언어에서 메시지 전달을 위해 pthread 라이브러리의 조건 변수를 사용할 수 있습니다. 조건 변수를 사용하여 스레드 간에 메시지를 전달하고 동기화할 수 있습니다.

#include <pthread.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;

int message = 0;

void *writer_function(void *arg) {
    pthread_mutex_lock(&mutex);

    // 메시지 전송
    message = 1;
    pthread_cond_signal(&condition);
    
    pthread_mutex_unlock(&mutex);
    return NULL;
}

void *reader_function(void *arg) {
    pthread_mutex_lock(&mutex);

    // 메시지 도착까지 대기
    while (message == 0) {
        pthread_cond_wait(&condition, &mutex);
    }
    
    // 메시지 처리
    printf("Message received: %d\n", message);
    
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    pthread_t writer_thread, reader_thread;

    pthread_create(&writer_thread, NULL, writer_function, NULL);
    pthread_create(&reader_thread, NULL, reader_function, NULL);

    pthread_join(writer_thread, NULL);
    pthread_join(reader_thread, NULL);

    return 0;
}

C언어에서 스레드 간 통신을 위해 공유 메모리와 메시지 전달을 사용할 수 있습니다. 이러한 방법을 활용하여 멀티스레드 프로그램을 효율적으로 작성할 수 있습니다.

더 많은 정보를 얻으시려면 아래 참조를 확인하세요.