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

Steven Schveighoffer schveiguy at gmail.com
Sun Aug 31 01:34:18 UTC 2025


On Sunday, 31 August 2025 at 00:46:50 UTC, Brother Bill wrote:
> The idea is that multiple shared objects use a common lock.
>
>
> ```d
> import std.stdio;
>
> void main()
> {
>
> }
>
> class BankAccount
> {
>
> }
>
> void transferMoney(shared BankAccount from,	shared BankAccount 
> to)
> {
> 	synchronized (from, to)    ← FAILS TO COMPILE.  Doesn't like 
> comma.
> 	{ // ← correct
> 		// ...
> 	}
> }
>
> ```
>
> This fails to compile with dmd 2.111.0
> ```
> c:\dev\D\81 - 90\c86_4f_multiple_synchronized\source\app.d(15): 
> Error: using the result of a comma expression is not allowed
>     synchronized (from, to)
>                   ^
> ```
>
> Is there another way to do this, other than manually, or is 
> this obsolete?

This syntax was intended to ensure synchronization always happens 
in a specified order (this text is in The D Programming Langauge 
book).

However, it was discovered that what actually happens is that 
only the last value is synchronized on, because this is simply a 
comma expression!

In a later version of D2, using the result of a comma expression 
was no longer allowed. This was to eliminate confusing errors 
(comma expression are seldom needed), and also to make way for 
using a sequence of expressions to mean a tuple (not yet in the 
language).

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


More information about the Digitalmars-d-learn mailing list