Shared with synchronized

Per Nordlöw per.nordlow at gmail.com
Mon Apr 19 08:38:55 UTC 2021


On Monday, 4 March 2019 at 00:07:39 UTC, r-const-dev wrote:
>> I'm trying to implement a thread safe class, guarding data 
>> access with synchronized and atomicOp.

To get more help with memory safety checking from the compiler, 
please instead use `@safe` as

```d
import std.typecons : Nullable;

@safe class SharedObject {
     private Nullable!int sharedValue;
     private int changeCount = 0;
     synchronized void modifyValue(int newValue) @trusted {
         (cast(SharedObject)this).unsafeModifyValue(newValue);
     }
     private void unsafeModifyValue(int newValue) {
         sharedValue = newValue;
         ++changeCount;
     }
}

@safe void main()
{
     shared SharedObject data = new shared SharedObject();
     data.modifyValue(3);
}
```


More information about the Digitalmars-d-learn mailing list