Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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