How synchronized actually works?

Hipreme msnmancini at hotmail.com
Fri Dec 1 21:01:32 UTC 2023


I was almost going to implement a thing which I would call 
`Locked`, by using that code:

```d
struct Locked
{
     private Mutex mtx;
     this(Mutex mtx)
     {
         this.mtx = mtx;
         mtx.lock();
     }
     ~this()
     {
         mtx.unlock();
     }
}

with(Locked(myMutex))
{
}
```

But then I remembered D has a keyword called `synchronized`. Then 
I looked at the spec, and I was overjoyed by the example present 
on it:


> Example
```d
synchronized { ... }
```

I really loved this example and I think it should be reproduced 
in a big screen everywhere in the world (complete sarcasm).

I'm wanting someone more experienced in the subject to both 
explain in this thread and update the spec: 
(https://dlang.org/spec/statement.html#synchronized-statement)

Also, there has been a talk on Discord for it being a Range-like 
interface, but for `lock` and `unlock`, instead of using only 
classes object but I don't understand enough about this subject.


More information about the Digitalmars-d mailing list