Search code examples
multithreadingd

Reading global value from multiple threads


C++ programmer here learning D. This is a very simplified example to demonstrate the issue I'm having in my real code. I'm fully aware of the code style issues with global variables, I just want to understand why this doesn't work.

I have a "global" variable which I initialize in the main program before creating any threads. I then have some threads that read that variable. It is never written to after it is set so there ought to be no race conditions reading it without synchronization after it is set.

But it doesn't work. I never see the value 12 in my threads, they always read the value 0. I know that in C++ you should use either a mutex or an std::atomic variable to ensure that values written in one thread are visible in another, and likely the same is true in D, however I would have assumed that the call to spawn is almost 100% likely to have done something to synchronize plus I experimented with a mutex and even when I tried to protect the value with a mutex I still see 12 in the main thread and 0 in the spawned thread.

Is there something I need to do to make this work?

No matter what I do I get :-

From thread A=0
From main   A=12

The code is :-

import std.concurrency;
import std.stdio;
import core.thread;

int a;

void myThread()
{
    writeln("From thread A=", a);
}

void main()
{
    a = 12;
    spawn(&myThread);
    Thread.sleep(2.seconds);
    writeln("From main   A=", a);
}

Solution

  • Variables in D are thread-local by default. Either use shared or __gshared.