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;
}
'OS > Homework' 카테고리의 다른 글
[운영체제] 연결리스트 구현하기 (0) | 2022.06.27 |
---|---|
[운영체제] Semaphore (0) | 2022.06.27 |
[운영체제] 쉘 프로그래밍 (0) | 2022.06.27 |
[운영체제] fork() 사용하기 (0) | 2022.06.27 |
[운영체제] 운영체제를 들어가기 전에 유닉스 복습하기 (0) | 2022.03.07 |