synchronized classes and shared

frame frame86 at live.com
Fri Aug 19 13:49:00 UTC 2022


On Friday, 19 August 2022 at 11:05:16 UTC, Loara wrote:

> `shared` means that data can be accessed by different threads, 
> indeed when you want to send a pointer to another thread the 
> pointed data must be `shared` even if it's a `synchronized` 
> class.

That is correct, however `shared` also has another meaning in 
concurrency in D. Consider that `getA()` would modify `a` then 
the compiler tells you to forget that and to use atomatic 
operations instead because `shared` is linked to them.

An atomic operation is a hardware instruction, synchronization is 
more or less software implemented. Very different things. So D 
says using `shared` is preparation for atomic operations that are 
considered more thread safe than any other mechanism and only 
allows such operations on objects that have that storage class, 
giving some guarantee if you are using it right (at least this is 
my understanding of it).

As synchronization needs a mutex, you would lose advantages of 
atomic and/or doing something wrong, so it makes no big sense to 
convert the code automatically or it could be an error too.


More information about the Digitalmars-d mailing list