我对并发编程很陌生,所以我有一个需要解决的死锁小问题。
因此,对于下面的这段代码,它不会打印出我怀疑一定存在死锁的任何内容,尽管我不太确定它是如何发生的。
let sleepMaybe() = if (random 4) = 1 then Thread.Sleep 5
type account(name:string) =
let balance = ref 1000
member this.Balance = lock this <| fun () -> !balance
member this.Name = name
member this.Withdraw amount = balance := !balance - (sleepMaybe(); amount)
member this.Deposit amount = balance := !balance + (sleepMaybe(); amount)
member this.Transfer (toAcc:account) amount =
lock this <| fun () -> lock toAcc <| fun () -> toAcc.Deposit amount
this.Withdraw amount
let doTransfers (acc:account) (toAcc:account) () =
for i in 1..100 do acc.Transfer toAcc 100
printfn "%s balance: %d Other balance: %d" acc.Name acc.Balance toAcc.Balance
let q2main() =
let acc1=account("Account1")
let acc2=account("Account2")
startThread (doTransfers acc1 acc2)
startThread (doTransfers acc2 acc1)
q2main()