On Monday, 4 March 2024 at 16:02:50 UTC, Andy Valencia wrote:
On Monday, 4 March 2024 at 03:42:48 UTC, Richard (Rikki) Andrew
Cattermole wrote:
... I still hope to be able to share memory between spawned
threads, and if it isn't a shared ref of a shared variable,
then what would it be? Do I have to use the memory allocator?
For any other newbie dlang voyagers, here's a version which works
as expected using the system memory allocator. On my little i7 I
get 1.48 secs wallclock with 5.26 CPU seconds.
import core.atomic : atomicFetchAdd;
import std.concurrency : spawn;
import core.time : msecs;
import core.thread : Thread;
import core.memory : GC;
const uint NSWEPT = 100_000_000;
const uint NCPU = 4;
void
doadd(shared uint *buf)
{
for (uint count = 0; count < NSWEPT/NCPU; ++count) {
atomicFetchAdd(buf[0], 1);
}
}
void
main()
{
shared uint *buf =
cast(shared uint *)GC.calloc(uint.sizeof * 1,
GC.BlkAttr.NO_SCAN);
for (uint x = 0; x < NCPU-1; ++x) {
spawn(&doadd, buf);
}
doadd(buf);
while (buf[0] != NSWEPT) {
Thread.sleep(1.msecs);
}
}