www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 21232] New: std.parallelism.parallel reuses thread, leading

https://issues.dlang.org/show_bug.cgi?id=21232

          Issue ID: 21232
           Summary: std.parallelism.parallel reuses thread, leading to
                    stale static data
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: industry
          Severity: blocker
          Priority: P1
         Component: phobos
          Assignee: nobody puremagic.com
          Reporter: pro.mathias.lang gmail.com

Test code:

```
import std.parallelism;
import std.process;
import std.range;
import std.stdio;
import core.atomic;

shared int initCount, liveCount;

static this ()
{
    atomicOp!("+=")(initCount, 1);
    atomicOp!("+=")(liveCount, 1);
}

static ~this ()
{
    atomicOp!("-=")(liveCount, 1);
}

class B
{
    int val;

    static B f()
    {
        static B b;
        if (b is null)
            b = new B();
        return b;
    }

}

void runTest (int i){
    B b = B.f();
    writeln("val is: ", b.val, "; thread id: ", thisThreadID);
    b.val = 2;
}

private void main()
{
    foreach (myVal; parallel(iota(0,9)))
        runTest(myVal);
    writefln("initCount: %d - liveCount: %d", initCount, liveCount);
}
```

Result:
```
val is: 0; thread id: 1149C4DC0
val is: 2; thread id: 1149C4DC0
val is: 2; thread id: 1149C4DC0
val is: 2; thread id: 1149C4DC0
val is: 0; thread id: 70000C529000
val is: 0; thread id: 70000C6B2000
val is: 0; thread id: 70000C62F000
val is: 0; thread id: 70000C5AC000
val is: 0; thread id: 70000C735000
initCount: 6 - liveCount: 6
```

IMO, this is just a disaster. Since threads are reused, the program will have
access to stale, static data. Type safety cannot be guaranteed because the
guarantees of module ctor / dtor are just thrown out the window.

We found this bug in our custom test runner, which handles priority, and run
many threads to speed up testing.

--
Sep 09 2020