OS/Homework

[운영체제] Race condition

달의요정루나 2022. 6. 27. 11:30

1. 다음 프로그램을 완성하여 race condition이 발생함을 확인하시오.

#include <stdio.h>
#include <pthread.h>

int money=1000;

int main(void)
{
	printf("I'm main thread\n");
	pthread_create(&id1, NULL, func1, NULL);
	pthread_create(&id2, NULL, func2, NULL);

	pthread_join(id1, &tret);
	pthread_join(id2, &tret);

	printf("money: %d\n", money);
}

void func1(void){
	for(i=0; i<100; i++){
		deposit(10);
		withdraw(10);
	}
}

void func2(void){
	for(i=0; i<100; i++){
		deposit(10);
		withdraw(10);
	}
}

int withdraw(amount){
	int balance;

	balance = get_balance();
	balance = balance - amount;
	put_balance(balance);

	return balance;
}

int deposit(amount){
	int balance;

	balance = get_balance();
	balance = balance + amount;
	put_balance(balance);

	return balance;
}

int get_balance(void)
{
	return money;
}

void put_balance(int balance)
{
	money = balance;
}

실행결과

 
 

2. 위의 문제에서 발생하는 race condition 문제를 해결하기 위하여 다음과 같이 lock 변수를 활용하는 예제를 구현하고, race condition 문제가 해결하시오

#include <stdio.h>
#include <pthread.h>

int money=1000;
int lock=0;

int main(void)
{
	printf("I'm main thread\n");
	pthread_create(&id1, NULL, func1, NULL);
	pthread_create(&id2, NULL, func2, NULL);

	pthread_join(id1, &tret);
	pthread_join(id2, &tret);

	printf("money: %d\n", money);
}

void func1(void){
	for(i=0; i<100; i++){
		deposit(10);
		withdraw(10);
	}
}

void func2(void){
	for(i=0; i<100; i++){
		deposit(10);
		withdraw(10);
	}
}

int withdraw(amount){
	int balance;

	while(lock != 0) ;
	lock = 1;

	balance = get_balance();
	balance = balance - amount;
	put_balance(balance);

	lock = 0;

	return balance;
}

int deposit(int amount){
	int balance;

	while(lock != 0) ;
	lock = 1;

	balance = get_balance();
	balance = balance + amount;
	put_balance(balance);

	lock = 0;

	return balance;
}