December 19

How does one really use atomics in D?

shared string[int] AA;
AA[s[2]].atomicStore(s[1]);

causes a hangup.

If I just assign it "works":

AA[s[2]] = s[1];

I've had similar issues where:

atomicOp!"+="(X[Y],1);

fails and I have to use

X[Y].atomicStore(1);

or

atomicOp!"+="(count,1); // fails (does not increment count)

so I have to create a new variable

int rcount = atomicFetchAdd(count,1);

and this will increment count.

In fact, I don't know what works or what doesn't except by trial and error. I don't even know how to go about thinking about these issues. In my mind, when using multiple threads and shared variables I try to use atomics to avoid any race conditions. Usually this involves incrementing or storing values. I try to use atomics that replace the single threaded concept but they do not always seem to work.

Are there any known issues or is it just me? Should it just work? is there any good reference that gets ones mind right for multithreading? I have some idea but I rarely do multithreading until lately(I guess because I now have the HP to care). I think the main issue I tend to have is trying to convert single threaded code in to multiple threads and missing certain key issues.

E.g.,

I was doing a parallel for and it wasn't really working(it seems the task pool stalls the entire pool until all tasks are complete):

for(s; parallel(arr))
{
// do stuff with s.
}

So I converted to using threads:

for(s; arr)
{
new Thread({
// do stuff with s.
}).start();
} // slightly more complex as I limited the total number of threads

But as I spun up threads I would get different threads working on the same s. I imagined that this likely had something to do with the variable being on the stack being reused. so I wrapped the thread in a function:

for(ss; arr)
{
void foo(typeof(ss) s)
{
new Thread({
// do stuff with s.
}).start();
}
foo(ss);
}

and this seemed to solve the problem. I imagine this is because ss is duped by the function call essentially detaching it from the loop code so it is unique across the thread.

But I guess I need to learn exactly how to deal with all these problems rather than just hacking away.