교착상태 예제

운영체제론 2015. 1. 6. 10:46

#include <stdio.h>

#include <pthread.h>

#include <Windows.h>


pthread_mutex_t first_mutex  = PTHREAD_MUTEX_INITIALIZER;

pthread_mutex_t second_mutex = PTHREAD_MUTEX_INITIALIZER;


int firstint = 0;

int secondint = 0;


// 첫 번째 스레드에 돌아갈 프로그램

void *do_work_one(void *pParam)

{

while(1)

{

pthread_mutex_lock(&first_mutex); // 1번뮤텍스 lock

pthread_mutex_lock(&second_mutex); // 2번뮤텍스 lock


firstint++;


pthread_mutex_unlock(&second_mutex); // 2번뮤텍스 unlock

pthread_mutex_unlock(&first_mutex); // 1번뮤텍스 unlock

}


pthread_exit(0);

}


// 두 번째 스레드에 돌아갈 프로그램

void *do_work_two(void *pParam)

{

while(1)

{

pthread_mutex_lock(&second_mutex); // 2번뮤텍스 lock

pthread_mutex_lock(&first_mutex); // 1번뮤텍스 lock


secondint++;

pthread_mutex_unlock(&first_mutex); // 1번뮤텍스 unlock

pthread_mutex_unlock(&second_mutex); // 2번뮤텍스 unlock

}


pthread_exit(0);

}


int main(int argc, char* argv[])

{

int thr_id1; // 스레드 id

int thr_id2; // 스레드 id

pthread_t p_thread; // 스레드 구조체

int thrfirst  = 1; // 1번 스레드 구분숫자

int thrsecond = 2; // 2번 스레드 구분숫자


thr_id1 = pthread_create(&p_thread, NULL, do_work_one, (void*)thrfirst);

thr_id2 = pthread_create(&p_thread, NULL, do_work_two, (void*)thrsecond);


while(1)

{

printf("first = %d\tsecond = %d\n", firstint, secondint); // 출력으로 쓰레드 동작 확인하기


Sleep(500); // 관찰을 위한 Sleep

}


pthread_mutex_destroy(&first_mutex); // 1뮤텍스 해제

pthread_mutex_destroy(&second_mutex); // 2뮤텍스 헤제


return 1;

}







pthread.h는 유닉스/리눅스 상에서 쓰이는 헤더인데


잘 검색해보면 윈도우용 dll lib h를 받을 수 있음


안쓰고 뮤텍스를 사용하는것도 가능한데 닷넷프레임워크 규칙에 따름. 이건 MSDN에서 검색

: