其他分享
首页 > 其他分享> > 操作系统 cha5

操作系统 cha5

作者:互联网

5.7 Race conditions

Question:Race conditions are possible in many computer systems. Consider a banking system that maintains an account balance with two functions: deposit(amount) and withdraw(amount). These two functions are passed the amount that is to be deposited or withdrawn from the bank account balance. Assume that a husband and wife share a bank account. Concurrently, the husband calls the withdraw() function and the wife calls deposit(). Describe how a race condition is possible and what might be done to prevent the race condition from occurring.

Answer:

A race condition occurs when both processes changes the shared variable-bank account balance at the same time.For example,the initial amount is 2000 dollars,now both husband and wife want to use this amount and do some changes:The husband reads the amount($2000),then he wants to withdraw $1000,time slice is over ;and his wife reads the amount(&2000),she deposits $3000,now the account has $5000 actually,but the account haven't been saved ,time slice is over;the husband withdraws $1000 now ,the account displays $1000 for him.But the account should display $4000,so the error occurs.

How to prevent the race condition?

do {
     flag[i] = true;
     turn = j;
     while (flag[j] && turn == j);
     critical section
     flag[i] = false;
     remainder section
} while (true);

i,j represents two processes.A critical section is a section that needs to be mutually exclusive, for example, when critical shared data needs to be modified. This section should not be modified by two processes at the same time, otherwise unpredictable results will occur.In remainder section ,operations can be performed parallel.Two processes enter mutually exclusive;the process in a non-remaider section can enter the critical section for a certain amount of time;Ensure that a process does not wait too long.

Let only one thread enter a critical section at a time. Once a thread enters a critical section, it is locked, and no other thread can access the critical section unless the thread itself releases the lock.

5.8 critical section problem

The first known correct software solution to the critical-section problem for two processes was developed by Dekker. The two processes, P0 and P1, share the following variables:

boolean flag[2]; /* initially false */
int turn; 

The structure of process Pi (i == 0 or 1) is shown in Figure 5.21. The other process is Pj (j == 1 or 0). Prove that the algorithm satisfies all three requirements for the critical-section problem.

Answer:

标签:操作系统,process,section,amount,turn,flag,critical,cha5
来源: https://blog.csdn.net/weixin_50497095/article/details/121294719