[OS] 14. Semaphore

dnjstjt12·2024년 11월 5일

Semaphore

  • 공유자원에 대해 지정된 개수의 Thread나 Process만 접근할 수 있는 방법

Busy-waiting Semaphore

typedef struct {
	int S;
}Semaphore;

void wait(Semaphore *semaphore){
	while(semaphore->S <= 0); //Busy wait
    semaphore->S--;
}
void signal(Semaphore *semaphore)  {
	semaphore->S++;
}
  • Busy-wait가 일어나는 단점이 있다.

Blocking Semaphore

typedef struct {
	int S;
    struct task *Q;
}Semaphore;

void wait(Semaphore *semaphore){
	semaphore->S--;
    if(semaphore->S<0){
    	add_task(semaphore->Q);
        block();
    }
}

void signal(Semaphore *semaphore){
	semaphore->S++;
    if(semaphore->S<0){
    	struct task P = remove_task(semaphore->Q);
        wakeup(P);
    }
}

Type

  • Binary semaphore: 세마포어 값이 1인 경우(Mutex lock이랑 같음)
  • Counting semaphore: 세마포어 값이 N인 경우
profile
안녕하세요!

0개의 댓글