Created
May 25, 2017 02:53
-
-
Save radcapricorn/f098461bf56979cecae3aa4996af31c6 to your computer and use it in GitHub Desktop.
initOnce, extra flag, no bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import core.thread; | |
import core.sync.semaphore; | |
import core.sync.mutex; | |
import core.atomic; | |
import std.stdio; | |
import std.typecons; | |
// 'extra' flag | |
shared bool initialized; | |
shared bool flag; | |
__gshared uint a; | |
__gshared uint b; | |
__gshared Mutex mtx; | |
auto makeGlobalWithInitOnce() | |
{ | |
if (!initialized) | |
{ | |
// this is an inline initOnce | |
if (!atomicLoad!(MemoryOrder.acq)(flag)) | |
{ | |
synchronized (mtx) | |
{ | |
if (!atomicLoad!(MemoryOrder.acq)(flag)) | |
{ | |
a = 1; | |
b = 1; | |
initialized = true; | |
atomicStore!(MemoryOrder.rel)(flag, true); | |
} | |
} | |
} | |
} | |
return tuple(a, b); | |
} | |
void threadFunc(int id, Semaphore start, Semaphore end) | |
{ | |
for (;;) | |
{ | |
start.wait; | |
auto ab = makeGlobalWithInitOnce(); | |
if (ab[0] != 1) writefln("bugbug in thread %d, reorder a", id); | |
if (ab[1] != 1) writefln("bugbug in thread %d, reorder b", id); | |
end.notify; | |
} | |
} | |
Thread spawnThread(int id, Semaphore start, Semaphore end) | |
{ | |
static class Impl : Thread { | |
int id; | |
Semaphore s, e; | |
this(int id, Semaphore s, Semaphore e) | |
{ | |
this.id = id; | |
this.s = s; | |
this.e = e; | |
super(&run); | |
} | |
void run() | |
{ | |
threadFunc(this.id, this.s, this.e); | |
} | |
} | |
auto thr = new Impl(id, start, end); | |
thr.start; | |
return thr; | |
} | |
void main() | |
{ | |
mtx = new Mutex; | |
Semaphore start1 = new Semaphore(); | |
Semaphore start2 = new Semaphore(); | |
Semaphore end = new Semaphore(); | |
auto t1 = spawnThread(1, start1, end); | |
auto t2 = spawnThread(2, start2, end); | |
for (;;) | |
{ | |
// reset state | |
a = 0; | |
b = 0; | |
flag = false; | |
initialized = false; | |
// propagate changes made above | |
asm { mfence; } | |
// allow threads to start next iteration | |
start1.notify; | |
start2.notify; | |
auto ab = makeGlobalWithInitOnce(); | |
if (ab[0] != 1) writeln("bugbug in main, reorder a"); | |
if (ab[1] != 1) writeln("bugbug in main, reorder b"); | |
// wait for both threads to finish their iteration | |
end.wait; | |
end.wait; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment