June 30, 2016 thread-safe shared field access | ||||
---|---|---|---|---|
| ||||
For example I have a shared from different threads variable. What piece of code is correctly thread-safe? First: shared class A { shared(int) x; void test1() { x = 10; x += 5 writeln(x); } } Or second: import core.atomic; shared class A { shared(int) x; void test1() { atomicStore(x, 10); atomicOp!("+=")(x, 5); writeln(atomicLoad(x)); } } |
June 30, 2016 Re: thread-safe shared field access | ||||
---|---|---|---|---|
| ||||
Posted in reply to jj75607 | On 6/30/16 10:10 AM, jj75607 wrote: > For example I have a shared from different threads variable. What piece > of code is correctly thread-safe? > > First: > shared class A > { > shared(int) x; Note, no need to mark x shared. 'A' implicitly shares everything. > > void test1() > { > x = 10; > x += 5 > writeln(x); > } > } > > Or second: > import core.atomic; > shared class A > { > shared(int) x; > > void test1() > { > atomicStore(x, 10); > atomicOp!("+=")(x, 5); > writeln(atomicLoad(x)); > } > } I don't believe the first will compile. This is probably the only thing that D adds for shared data (it enforces that you use atomics to read or modify shared primitives). And yes, the second is correct while the first is not. Note that writeln is still writing a copy of the atomically loaded x. you could as easily done: auto xcopy = atomicOp!("+=")(x, 5); writeln(xcopy); To avoid the atomic load. -Steve |
Copyright © 1999-2021 by the D Language Foundation