[c언어] 뮤텍스(mutex)와 세마포어(semaphore)

동시에 여러 스레드나 프로세스가 공유 자원에 접근하는 경우, 문제가 발생할 수 있습니다. 이런 문제를 해결하기 위해 뮤텍스세마포어라는 동기화 기법이 사용됩니다.

1. 뮤텍스(Mutex)

뮤텍스는 임계 영역에 대한 접근을 제어하기 위한 동기화 기법입니다. 오직 하나의 스레드만 임계 영역에 접근할 수 있도록 합니다.

예시 코드:

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

pthread_mutex_t lock;

void* critical_section(void* arg) {
    pthread_mutex_lock(&lock);
    // 임계 영역
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main() {
    pthread_t t1, t2;
    pthread_mutex_init(&lock, NULL);
    pthread_create(&t1, NULL, critical_section, NULL);
    pthread_create(&t2, NULL, critical_section, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_mutex_destroy(&lock);
    return 0;
}

2. 세마포어(Semaphore)

세마포어는 한정된 개수의 자원을 관리하기 위한 동기화 도구로, 이를 사용하여 임계 영역에 동시에 접근할 수 있는 스레드의 개수를 조절할 수 있습니다.

예시 코드:

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

sem_t semaphore;

void* critical_section(void* arg) {
    sem_wait(&semaphore);
    // 임계 영역
    sem_post(&semaphore);
    return NULL;
}

int main() {
    pthread_t t1, t2;
    sem_init(&semaphore, 0, 1);
    pthread_create(&t1, NULL, critical_section, NULL);
    pthread_create(&t2, NULL, critical_section, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    sem_destroy(&semaphore);
    return 0;
}

3. 결론

프로그램이 정확하게 동작하고 자원에 안전하게 접근하기 위해서는 뮤텍스와 세마포어와 같은 동기화 기법이 필수적입니다. C언어에서는 이러한 기법을 사용하여 다중 스레드나 프로세스 간의 동기화를 보장할 수 있습니다.

4. 참고 자료