Comment #0 by petar.p.kirov — 2016-06-30T01:42:00Z
The current implementation of `synchronized` leaves much to be desired:
1. It adds the overhead of a monitor field to every class, even when it's never used. Also makes object creation / finalization in druntime more complex.
2. It requires that all monitors/mutexes are implemented as classes, derived from Object.Monitor, which also excludes struct-based implementations.
3. It does not allow custom implementation - e.g. `struct` objects can't be synchronized.
4. Can't be `nothrow`/`@nogc`/etc. by design - because `Object.Monitor` tries to be maximally inclusive, similarly to the Object.op* attribute problem.
Instead there should be a well defined, easily accessible protocol (e.g. `opLock`, `opUnlock`, `opTryLock` non-static member functions) that is recognized by the compiler (similar to how it already recognizes both struct and class based input ranges) which would be used whenever `obj` in `synchronized (obj)` implements it.
Another option would be to allow users to implement the `__monitor` field themselves, provided that it has the required methods (at least `lock` and `unlock` or `opLock`/`opUnlock`).
A third option would be to allow user overloads (non-extern) of `_d_monitorenter` `_d_monitorexit` as free functions that are looked up similarly to how `std.math.pow` is for the `^^` operator.
Comment #1 by robert.schadek — 2024-12-13T18:48:46Z