Shared, but synchronisation is not desired for multithreading
tcak via Digitalmars-d
digitalmars-d at puremagic.com
Sat Jun 4 08:11:51 PDT 2016
If you ignore the discouraged __gshared keyword, to be able to
share a variable between threads, you need to be using "shared"
keyword.
While designing your class with "shared" methods, the compiler
directly assumes that objects of this class must be protected
against threading problems.
There can be three USAGEs of a class object:
1. It will be non-shared. So, it is stored in TLS, and only one
thread can access it.
2. It will be shared. But programmer knows that the object is
designed as "shared" with the purpose of reading its value from
multiple threads.
3. It will be shared. But the object must be synchronised.
Because programmer knows that multiple threads will be reading
from and writing to object.
Currently, in a normal coding environment (I am not talking about
using extra parameters, increasing complexity etc),
distinguishing between 2 and 3 does not seem like possible. You
prepare your shared class, and its methods are designed to be
either sycnhronised or not synchronised. There is no middle point
unless you define the same method with different names, or use a
flag like "bool run_this_method_synchronised_please".
So, what I did is using UDA for this with the name @ThreadSafe.
e.g.
@ThreadSafe auto myObject = new shared MyClass();
In a method of the class, I make the declaration as following:
public void foo() shared{
static if( std.traits.hasUDA!( this, ThreadSafe ) ){
// lock mutex
scope(exit){
// unlock mutex
}
}
// do your normal operations
}
This way, if the object is desired to be doing synchronisation,
you only add an attribute to it.
There are some small problems here, those are related to D's
implementation right now:
1. There is no standard way of saying @ThreadSafe. You are
supposed to be defining it. If language was to be defining a
standard attribute as @ThreadSafe, it could be used everywhere
for this purpose.
2. If a method is defined as shared, compiler immediately warns
the programmer to use core.atomic.atomicOp. If codes are already
being designed as thread-safe by the programmer, normal variable
operations could be used without any concern.
3. As far as I remember, there were some talks about synchronized
keyword not being used much. Maybe its usage could be changed to
support this @ThreadSafe system.
More information about the Digitalmars-d
mailing list