5 ms·
> we can implement a correct version of transfer(amount:to:) // Safe: this operation is the only one that has access to the actor's isolated // state r
by mrkeen 6y ago
> we can implement a correct version of transfer(amount:to:)
// Safe: this operation is the only one that has access to the actor's isolated
// state right now, and there have not been any suspension points between
// the place where we checked for sufficient funds and here.
balance = balance - amount
// Safe: the deposit operation is placed in the `other` actor's mailbox; when
// that actor retrieves the operation from its mailbox to execute it, the
// other account's balance will get updated.
await other.deposit(amount: amount)
Am I correct in thinking that the system temporarily destroys money here (and hopes to recreate it if the receiver doesn't crash?)
If I have a closed system of actors constantly transferring money among themselves, and I poll to see the total amount of money in the system, will it fluctuate?
- liuliu 6y agoI think that you are correct. There is a paragraph on actor's reentrancy: https://github.com/apple/swift-evolution/blob/main/proposals/0306-actors.md#actor-reentrancy https://github.com/apple/swift-evolution/blob/main/proposals... which points out that you can definitely get balance before await, therefore, have fluctuated total.
- rkalla 6y agoIn the code above it certainly looks like that - is this not idiomatic swift-finance code though?
- syrrim 6y agoThey say that the `deposit` call is placed in `other`s mailbox. As long as the mailbox is preserved between restarts, then there is no danger of the money disappearing. The money will temporarily be unavailable - that is, in neither account's balance. But the money is still somewhere, in the mailbox.
- gpderetta 6y agoA crash between updating balance and putting the message in the mailbox can still result in an inconsistent state.
- msoad 6y agoThere is also Swift Atomics[1] that is probably needed here [1] https://swift.org/blog/swift-atomics/ https://swift.org/blog/swift-atomics/
- ogre_codes 6y agoI was thinking the same thing as I read this. Keep in mind, these examples are meant to illustrate how Actors work, not how to write good banking code.
- centimeter 6y agoThis is an especially poor choice of example given that it's the canonical example for STM, and STM actually solves the problem.
- jayd16 6y agoYou're assuming you can read balance in a dirty way, but it seems like you would call an async GetBalance() method that could not read the value of balance until transfer has fully completed. Any experts that can confirm this?
- helge9210 6y agoTLDR: account balance is not a good example to simply explain actors. Actor model in general doesn't guarantee the ordering of the messages. The is possibility that all the withdraw messages arrive first and all the deposits later. Balance poll result makes sense only with assumption "all messages before this point of time have been processed"