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

Steven Schveighoffer schveiguy at gmail.com
Sun Aug 31 10:52:10 UTC 2025


On Sunday, 31 August 2025 at 03:45:07 UTC, Ali Çehreli wrote:
> 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)
> > {
> >     ...
> > }
> > ```
>
> 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.

D has never supported this.

 From the book:

> Note: This feature is not supported by dmd 2.098.1.

This should read:

> Note: this feature has never been implemented and before DMD 
> 2.098.1 this syntax would compile and do the wrong thing.

Which is why I recommend removing the whole discussion.

If you want to ensure some order of locking you need to do it 
manually. Even before 2.098.1

-Steve




More information about the Digitalmars-d-learn mailing list