Created
December 28, 2014 09:13
-
-
Save anibali/4d544c31ac762409d4ea to your computer and use it in GitHub Desktop.
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 std.stdio: writeln, writefln; | |
import core.thread: Thread; | |
import core.sync.mutex: Mutex; | |
import core.atomic: atomicOp; | |
shared class SharedClass { | |
int x = 0; | |
Mutex mutex; | |
this() { | |
// mutex = new shared Mutex; // Error: None of the overloads of '__ctor' are | |
// callable using a shared object | |
mutex = cast(shared)new Mutex; | |
} | |
private void workFunction() { | |
// mutex.lock(); // Error: non-shared method | |
(cast(Mutex)mutex).lock(); | |
writefln("x was %d", x); | |
x.atomicOp!"+="(1); | |
writefln("x is now %d", x); | |
// mutex.unlock(); // Error: non-shared method | |
(cast(Mutex)mutex).unlock(); | |
} | |
void doWork() { | |
writeln("Starting work..."); | |
Thread[5] threads; | |
foreach(i; 0..threads.length) { | |
// threads[i] = new Thread(&workFunction); // Error: None of the overloads | |
// of '__ctor' are callable | |
// using argument type | |
// (void delegate() shared) | |
threads[i] = new Thread(cast(void delegate())&workFunction); | |
threads[i].start(); | |
} | |
} | |
} | |
void main() { | |
auto sharedClass = new shared SharedClass(); | |
sharedClass.doWork(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment