What sync object should i use?
Juan Manuel Cabo
juanmanuel.cabo at gmail.com
Mon May 13 14:04:22 PDT 2013
On Monday, 13 May 2013 at 20:44:37 UTC, Heinz wrote:
> Ok, here's a summary in case someone else is in the same need:
>
> 1) Want to know what "mutex/condition" are, how do they work
> and when to use them? Here's a good resource:
> http://stackoverflow.com/a/4742236
>
> 2) If you come to the question "Why a condition needs a
> mutex?":
> http://stackoverflow.com/questions/2763714/why-do-pthreads-condition-variable-functions-require-a-mutex
>
> 3) Need a working example in D? (by Steven Schveighoffer):
> http://forum.dlang.org/thread/j7sdte$25qm$1@digitalmars.com
Here is the absolute minimum of code I could think to try
Condition. I tested it on linux 64bits and windows 32bits. There
is one thing that should definitely added to the documentation,
and that is what happens when one issues a notify while the
thread hasn't yet called Condition.wait().
I seem to recall (though I might be wrong) that win32 events can
be signalled before the thread calls WaitForSingleObject (or
WaitForMultipleObjects), and if it was signalled, the call
returns immediately. I think this was very useful.
import std.stdio, core.thread, core.sync.condition,
core.sync.mutex;
//Note: The condition must be __gshared:
__gshared Condition condition;
__gshared Mutex mutex;
private void myThread() {
writeln("Started");
synchronized(mutex) {
condition.wait();
}
writeln("Notified");
}
void main() {
mutex = new Mutex();
condition = new Condition(mutex);
Thread theThread = new Thread(&myThread);
theThread.start();
//Note: if one doesn't wait for the thread to
//get to condition.wait(), before calling notify(),
//the thread is not awaken. (ie: commenting the
//sleep makes the thread stuck).
Thread.sleep(dur!"msecs"(100));
synchronized(mutex) {
condition.notify();
}
theThread.join();
writeln("main finished");
}
More information about the Digitalmars-d-learn
mailing list