Bug 2162 – Access violation when threads run closures
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2008-06-22T17:20:00Z
Last change time
2015-06-09T01:19:51Z
Assigned to
nobody
Creator
bartosz
Comments
Comment #0 by bartosz — 2008-06-22T17:20:22Z
Passing closures to threads might be considered an error, but the current thread implementation virtualy encourages it. The program below behaves erratically--the starting value of x and y inside thread functions is random and, at leas in my environment, the program access violates. (I'm not sure how reproducible it is).
void test(ref Thread thr1, ref Thread thr2)
{
int x, y;
int run1()
{
writeln("Run1 ", x);
for(int i = 0; i < 100000; ++i)
++x;
writeln("End Run1 ", x);
return 0;
}
int run2()
{
writeln("Run2 ", y);
for(int i = 0; i < 100000; ++i)
++y;
writeln("End Run2 ", y);
return 0;
}
thr1 = new Thread(&run1);
thr2 = new Thread(&run2);
}
void main()
{
try
{
Thread thr1, thr2;
test(thr1, thr2);
thr1.start();
thr2.start();
thr1.wait();
thr2.wait();
}
catch(Exception e)
{
writeln ("Exception in main: ", e.toString);
}
}
Comment #1 by bruno.do.medeiros+deebugz — 2008-10-03T08:43:58Z
Bump! I've recently run into this as well.
The problem happens when the context of the passed delegate is in the stack.
If the context of the passed delegate is in the heap, all is fine. If you add this code to th end of test():
...
thr1 = new Thread(&run1);
thr2 = new Thread(&run2);
auto dummy = (&run1);
}
---
The program will run correctly, as the context will be on the heap.
So I think the problem might just be incorrect closure detection?
Comment #2 by andrej.mitrovich — 2011-05-24T22:45:34Z
In 2.053 it will deny compiling this as it detects that run1 and run2 are delegates.