sicp-ex-3.41



<< Previous exercise (3.40) | Index | Next exercise (3.42) >>


xdavidliu

serializing balance is not necessary because getting the balance *doesn't change the state of the account*. Even if you serialize the balance accessor, a parallel execution of a series of withdraw!'s deposit!'s and balance's will still occur in an undefined order. Hence, any ambiguities that would occur when the balance accessor is *not* serialized would still occur if it *is* serialized.

When balance is not serialized, then calls to balance may interleave into a call to withdraw! or deposit!. However, since there is only one call to set! in each of these functions, balance will still either get only the "before" or "after" values of the balance, and not some "intermediate" value that is neither the value before or after the withdraw! or deposit!

Hence, whether we serialize the balance accessor or not, we will always get the same results.


meteorgan

  
  
 No, if you get balance in different order with withdraw and deposit, you will get different result. but all they all legal. 

I disagree. I think the answer is yes. Another process could access balance mid-withdraw or mid-deposit and get the wrong info.


It's not wrong info. If a withdraw or deposit isn't finished, then the original balance is still valid. Accessing balance is a single operation, it cannot be interleaved with other procedures. Therefore, we don't need to protect it.


I believe the book uses these two requirements on concurrency:

  • First, it does not require the processes to actually run sequentially, but only to produce results that are the same as if they had run sequentially.
  • Second, there may be more than one possible ``correct'' result produced by a concurrent program, because we require only that the result be the same as for some sequential order.

An "unprotected" access to balance fulfills both requirements so I would say it does not really matter.

IMHO it is better to think about one real life example here. This problem is just https://en.wikipedia.org/wiki/Hazard_(computer_architecture)#Read_after_write_(RAW) IMHO.

Assume A and B shares one account. Then A tries to check balance before doing withdraw. Simultaneously B is doing withdraw and made "Insufficient funds". If balance method is not protected. Then A will be happy to do withdraw then. Then A gets one unexpected message "Insufficient funds". But A has known balance is not Insufficient due to the beforehand checking. So A may be confusing and doubted whether that sharing account password is leaked and money is stolen and then A asks bank employer for help which take much more time than just waiting for B to finish withdraw. So this will waste A time unnecessarily.