Synchronization on immutable object

Johan Engelen via Digitalmars-d digitalmars-d at puremagic.com
Tue Mar 22 03:49:01 PDT 2016


Quiz: does this compile or not?
```
class Klass {}
void main() {
     immutable Klass klass = new Klass;
     synchronized (klass)
     {
         // do smth
     }
}
```

A D object contains two (!) hidden pointers. Two? Yes: the vtable 
pointer __vptr, and a pointer to a Monitor struct which contains 
a synchronization mutex.
The synchronized statement is lowered into druntime calls that 
*write* to __monitor.
Quiz answer: yes it compiles. Oops?

This is related to an earlier discussion on whether TypeInfo 
objects should be immutable or not [1]. Should one be able to 
synchronize on typeid(...) or not?
```
interface Foo {}
void main() {
     synchronized(typeid(Foo)) {
        // do smth
     }
}
```
Because LDC treats the result of typeid as immutable, the code is 
bugged depending on the optimization level.

[1] 
http://forum.dlang.org/post/entjlarqzpfqohvnnwjb@forum.dlang.org


More information about the Digitalmars-d mailing list