I’m encountering a problem. Given the following code:
void withdraw(int x){
if (balance > x) balance = balance –x;
else cout << ”failed”;
};
Assume balance = 10, process A calls withdraw(5) and process B calls withdraw(7) at the
same time. List all possible outputs.
According to the Page 258 of Operating System Concepts – 10th Edition by Abraham Silberschatz and this lecture by the University of Delaware the shared variable are stored on two different registers. If applying this to my problem, a wrong output would be:
- Process A saves balance = 10 to register 1.
- Process B saves balance = 10 to register 2.
- Register 1 = Register 1 – amount
- Register 2 = Register 2 – amount
- balance = register 1 (balance = 5)
- balance = register 2 (balance = 3)
This means that one result would be overwritten depends on which register assigns to the shared variable balance first. If I
However, when I tried to simulate this scenario (added a new line at the end of the function to display the balance) using the multiprocessing module in Python. There are different results:
- Process A wrote 5, process B failed
- Process B wrote 3, process B failed
- Process A wrote 5, process B wrote -2 (and vice versa)
- Process A wrote 3, process B wrote 3
I’m wondering, if these two processes wrote the shared variable on two different registers, how could the third result be possible?
And how did the last result happen? And I also wonder where are the result in which Process A wrote 3, process B wrote 5. Any help would be great! Thank you!