세마포어란 멀티프로세싱 환경에서 복수의 프로세스에 의해 동시에 사용되서는 안되는 공유자원(메모리 등)의 접근을 제한하는 대표적인 방법. 교차로에서 '신호등'과 같은 역할을 한다.

세마포어두 개atomic function으로 조작되는 정수변수.

atomic function 이란? → 중단없이 나눠지지 않고 한번에 실행되는 함수.

그럼 그 2개의 atomic function은 어떤 역할?

P(S)

V(S)

동작 과정

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2c1c202e-c076-4650-8b06-9b441fbab632/Untitled.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/f90dc909-6acb-4cf9-ae61-6dc66a4644f9/Untitled.png

라즈베리 파이에서 세마포어 구현.

semaphore.h 헤더파일에 포함된 아래 3개의 함수를 '사용'하여 3대의 기차가 교차로를 순차적으로 통과하도록 프로그래밍.

  1. sem_init (세마포어 초기화 함수)
  2. sem_wait ( P(S)역할, critical section에 진입하기 위해 대기하는 함수 )
  3. sem_post ( V(S)역할, 자원을 다 사용한 후 반환하는 함수)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

//세마포어 정의
sem_t semaphore;

void *thread_train(void *i){
	int train_num = *((int*)i);
	// wait P(S) 함수
	sem_wait(&semaphore);
	printf("%d번 기차가 교차로를 통과했습니다. \\n", train_num);
	
	// V(S) 함수
	sem_post(&semaphore);
	free(i);
}

int main() {
	// 세마포어 생성
	sem_init(&semaphore, 0, 1);
	pthread_t t[3];
	int *intPtr;

	// 3개의 쓰레드 생성(3대의 기차로 가정)
	for (int i = 0; i < 3; i++) {
		int train_num = i+1;
		intPtr = (int*)malloc(sizeof(int));
		*intPtr = i + 1;
		pthread_create(&t[i], NULL, thread_train, (void*)intPtr);
	}

	pthread_join(t[0], NULL);
	pthread_join(t[1], NULL);
	pthread_join(t[2], NULL);

	sem_destroy(&semaphore);
	return 0;
}

실행결과