How to have multiple synchronized shared types. Programming in D, page 647

Ali Çehreli acehreli at yahoo.com
Sun Aug 31 03:45:07 UTC 2025


On 8/30/25 6:34 PM, Steven Schveighoffer wrote:

 > The original feature never worked as intended. That section of the book
 > should be removed.
 >
 > The correct way to do this is a nested synchronized statement:
 >
 > ```d
 > synchronized(from) synchronized(to)
 > {
 >     ...
 > }
 > ```
 >
 > -Steve

That's a recipe for a deadlock though: Imagine the same function is 
running for two bank accounts (A and B), each sending money to each other.

In one case, 'from' is A, and 'to' is B. In the other case, 'from' is B, 
and 'to' is A.

One thread locks A and the other locks B, then they both wait for the 
other forever.

When the language lacks a canonical order for multiple locks, the 
programmer must come up with a scheme to sort them and attempt to lock 
in the same order in both threads.

Ali



More information about the Digitalmars-d-learn mailing list