Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are locking on the instances themselves and requiring that both instances be locked to transfer something. That is a recipe for deadlocks.</p> <ul> <li>Thread 1 locks on acc1 to begin a transfer</li> <li>Thread 2 locks on acc2 to begin a transfer</li> <li>Thread 1 waits for the lock on acc2 to be released so it can complete its transfer</li> <li>Thread 2 waits for the lock on acc1 to be released so it can complete its transfer</li> </ul> <p>They will each wait for each other to let go of their lock indefinitely.</p> <p>If you <em>have</em> to acquire multiple locks at once, <em>always</em> acquire the locks in the same order. That said, try your best not to need more than one lock at once by changing your object responsibilities. </p> <p>For example, withdrawal and depositing are two separate actions that aren't related, but they modify the balance. You are trying to protect <em>the balance</em> with locks. Once an account's balance is changed, there's no point in keeping that lock anymore. Additionally, I would suggest that it's not the responsibility of an account to know how to transfer to other accounts. </p> <p>With that in mind, here are changes that eliminate the deadlock.</p> <pre><code>type Account(name:string) = let mutable balance = 1000 let accountSync = new Object() member x.Withdraw amount = lock accountSync (fun () -&gt; balance &lt;- balance - amount) member x.Deposit amount = lock accountSync (fun () -&gt; balance &lt;- balance + amount) let transfer amount (fromAccount:Account) (toAccount:Account) = fromAccount.Withdraw(amount) toAccount.Deposit(amount) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload