Does anyone understand how to use "shared" types with concurrency send/receive functions?
crimaniak via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Aug 20 19:17:57 PDT 2017
On Monday, 14 August 2017 at 03:59:48 UTC, Jonathan M Davis wrote:
> And no, this isn't ideal, but the only semi-decent solution
> that's been proposed that safely casts away shared for you is
> synchronized classes, which Andrei describes in TDPL but have
> never been implemented.
After reading this I did some experiment to understand the
situation better. I make a simple class and unittest:
// dmd sync1.d -unittest -main
unittest
{
import std.stdio;
synchronized
class A
{
private int a;
void inc()
{
++a;
}
int get(){ return a;}
}
shared A a;
for(int i=0; i<100; ++i)
a.inc();
writeln(a.get);
}
Oops! Deprecation: read-modify-write operations are not allowed
for shared variables. Use core.atomic.atomicOp!"+="(this.a, 1)
instead.
Why use atomic operations if the class already synchronized?
Well..
...
import core.atomic: atomicOp;
...
// ++a; // Deprecation: read-modify-write operations are not
allowed for shared variables. Use
core.atomic.atomicOp!"+="(this.a, 1) instead.
atomicOp!"+="(this.a, 1);
...
ok, works. But it works by the way as if synchronized just makes
all methods shared, but does not provide the object methods with
a mutex lock, as Java does. Am I right here? And what preventing
to implement it right, lack of manpower or some ideologic
problems?
More information about the Digitalmars-d-learn
mailing list