세마포어를 사용해서 뮤텍스 교착상태를 회피하기
운영체제론 2015. 1. 6. 18:02#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <Windows.h>
pthread_mutex_t mutex1; // 뮤텍스
pthread_mutex_t mutex2; // 뮤텍스
sem_t sem1; // 세마포어
sem_t sem2; // 세마포어
int intp1 = 0; // 1번 스레드 동작 확인
int intp2 = 0; // 2번 스레드 동작 확인
// 첫 번째 스레드에 돌아갈 프로그램
void *do_work_one(void *pParam)
{
while(1)
{
sem_wait(&sem1); // 세마포어 1번 카운터 감소 카운터가 0이면 무시
pthread_mutex_lock(&mutex1); // 1번뮤텍스 lock
pthread_mutex_lock(&mutex2); // 2번뮤텍스 lock
intp1++; // 값 증가
pthread_mutex_unlock(&mutex2); // 2번뮤텍스 unlock
pthread_mutex_unlock(&mutex1); // 1번뮤텍스 unlock
sem_post(&sem2); // 세마포어 2번 카운터 증가
}
pthread_exit(0);
}
// 두 번째 스레드에 돌아갈 프로그램
void *do_work_two(void *pParam)
{
while(1)
{
sem_wait(&sem2); // 세마포어 2번 카운터 감소 카운터가 0이면 무시
pthread_mutex_lock(&mutex2); // 2번뮤텍스 lock
pthread_mutex_lock(&mutex1); // 1번뮤텍스 lock
intp2++; // 값 증가
pthread_mutex_unlock(&mutex1); // 1번뮤텍스 unlock
pthread_mutex_unlock(&mutex2); // 2번뮤텍스 unlock
sem_post(&sem1); // 세마포어 1번 카운터 증가
}
pthread_exit(0);
}
int main(int argc, char* argv[])
{
pthread_t p_thread1; // 스레드 구조체1
pthread_t p_thread2; // 스레드 구조체2
pthread_mutex_init(&mutex1, NULL); // 스레드 초기화
pthread_mutex_init(&mutex2, NULL); // 스레드 초기화
sem_init(&sem1, 0, 1); // 세마포어 초기화 카운터값 1
sem_init(&sem2, 0, 0); // 세마포어 초기화 카운터값 0
pthread_create(&p_thread1, NULL, do_work_one, NULL); // 스레드 생성
pthread_create(&p_thread2, NULL, do_work_two, NULL); // 스레드 생성
while(1)
{
printf("first = %d\tsecond = %d\n", intp1, intp2); // 출력으로 쓰레드 동작 확인하기
Sleep(400); // 관찰을 위한 Sleep
}
pthread_mutex_destroy(&mutex1); // 1뮤텍스 해제
pthread_mutex_destroy(&mutex2); // 2뮤텍스 헤제
sem_destroy(&sem1); // 세마포어 해제
sem_destroy(&sem2); // 세마포어 해제
return 1;
}
전에 쓴 교착상태 예제소스를 세마포어를 추가하여 회피시키기
'운영체제론' 카테고리의 다른 글
세마포어를 사용해서 뮤텍스 교착상태 회피하기 (2) (0) | 2015.01.06 |
---|---|
교착상태 예제 (3) (0) | 2015.01.06 |
교착상태 예제 (2) (0) | 2015.01.06 |
교착상태 예제 (0) | 2015.01.06 |
교착상태(Deadlock) (0) | 2015.01.05 |