운영체제 OS

[운영체제/OS] POSIX Semaphore 동기화

POSIX Semaphore

-Named semaphore

여러 프로세스에서 공유할 수 있다.

#include <semaphore.h>
sem_t *sem;

/*create the semaphore and initialize it to 1*/
sem = sem_open("SEM", O_CREAT, 0666, 1);

/*acquire the semaphore*/
sem_wait(sem);

/*critical section*/

/*release the semaphore*/
sem_post(sem);

-Unnamed semaphore

#include <semaphore.h>
sem_t sem;

/*create the semaphore and initialize it to 1*/
sem_init(&sem, 0, 1);

/*acquire the semaphore*/
sem_wait(&sem);

/*critical section*/

/*release the semaphore*/
sem_post(&sem);

 

POSIX 조건 변수

pthread_mutex_lock(&mutex);
while(a!=b)
	pthread_cond_wait(&cond_var, &mutex);
pthread_mutex_unlock(&mutex);

pthread_mutex_lock(&mutex);
a=b;
pthread_cond_signal(&cond_var);
pthread_mutex_unlock(&mutex);