how does 'shared' affect member variables?

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 9 13:19:28 PDT 2015


On Saturday, 9 May 2015 at 18:41:59 UTC, bitwise wrote:
> What does 'shared' do to member variables?

Makes them `shared`. :P

> It makes sense to me to put it on a global variable, but what 
> sense does it make putting it on a member of a class?

Globals are not the only way to pass data to other threads. E.g., 
you can std.concurrency.send a shared Object:

----
import core.thread: thread_joinAll;
import std.concurrency;
class C {int x;}
void main()
{
     auto c = new shared C;
     c.x = 1;
     auto tid = spawn(() {
         receive(
             (shared C c) {c.x = 2;}
         );
     });
     send(tid, c);
     thread_joinAll();
     assert(c.x == 2);
}
----

That shared C could come from a class/struct member, of course.

> What happens if you try to access a member of a class/struct 
> instance from another thread that is not marked 'shared'?

I think you're not supposed to be able to do that.


More information about the Digitalmars-d-learn mailing list