#!/usr/bin/env dub
/+ dub.sdl:
name "handoff_latency"
dflags "-preview=dip1000" "-preview=in"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/**
The round-trip time of handing a turn between two threads that sleep while
waiting, for `docs/research/fine-grained-locking/comparison.md` § (d), fibers
waiting on a word. Three mechanisms:
- `futex`: a word per direction, `FUTEX_WAIT` on it and `FUTEX_WAKE` after
storing — what a wait-on-address primitive costs at its floor.
- `eventfd`: a counter per direction, a blocking `read` and a `write` — what
an event loop's file-descriptor waker costs.
- `pthread cond`: a mutex and a condition variable, the turn kept under the
mutex — druntime's `core.sync.condition.Condition`.
Every wait really sleeps: there is no spinning before it, so the numbers are
the cost of a sleep and a wake-up, scheduler latency included. They vary
between machines; on one they compare the mechanisms.
Linux only; elsewhere it prints `SKIP:` and exits 0.
*/
module (module) handoff_latencyThe round-trip time of handing a turn between two threads that sleep while
waiting, for docs/research/fine-grained-locking/comparison.md § (d), fibers
waiting on a word. Three mechanisms:
futex: a word per direction, FUTEX_WAIT on it and FUTEX_WAKE after
storing — what a wait-on-address primitive costs at its floor.
eventfd: a counter per direction, a blocking read and a write — what
an event loop's file-descriptor waker costs.
pthread cond: a mutex and a condition variable, the turn kept under the
mutex — druntime's core.sync.condition.Condition.
Every wait really sleeps: there is no spinning before it, so the numbers are
the cost of a sleep and a wake-up, scheduler latency included. They vary
between machines; on one they compare the mechanisms.
Linux only; elsewhere it prints SKIP: and exits 0.
handoff_latency;
version (linuxlinux)
version = (version) linuxBenchlinuxBench;
version (linuxBenchlinuxBench) {} else
{
void main()
{
import std.stdio : writeln;
writeln("SKIP: the futex and eventfd mechanisms need Linux");
}
}
version (linuxBenchlinuxBench):
import (package) corecore.(module) core.atomicThe atomic module provides basic support for lock-free
concurrent programming.
Use the -preview=nosharedaccess compiler flag to detect
unsafe individual read or write operations on shared data.
Source
core/atomic.d
Examples
int y = 2;
shared int x = y; // OK
//x++; // read modify write error
x.atomicOp!"+="(1); // OK
//y = x; // read error with preview flag
y = x.atomicLoad(); // OK
assert(y == 3);
//x = 5; // write error with preview flag
x.atomicStore(5); // OK
assert(x.atomicLoad() == 5);
atomic : (alias template) handoff_latency.atomicLoad = core.atomic.atomicLoad(MemoryOrder ms = MemoryOrder.seq, T)(auto ref return scope const T val) if (!is(T == shared(U), U) && !is(T == shared(inout(U)), U) && !is(T == shared(const(U)), U))Loads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad, (alias template) handoff_latency.atomicStore = core.atomic.atomicStore(MemoryOrder ms = MemoryOrder.seq, T, V)(ref T val, V newval) if (!is(T == shared) && !is(V == shared))Writes 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore;
import (package) corecore.(package) core.syncsync.(module) core.sync.conditionThe condition module provides a primitive for synchronized condition
checking.
Source
core/sync/condition.d
condition : (class) core.sync.condition.ConditionThis class represents a condition variable as conceived by C.A.R. Hoare. As
per Mesa type monitors however, "signal" has been replaced with "notify" to
indicate that control is not transferred to the waiter when a notification
is sent.
Examples
import core.sync.mutex;
import core.sync.semaphore;
import core.thread;
void testNotify()
{
auto mutex = new Mutex;
auto condReady = new Condition( mutex );
auto semDone = new Semaphore;
auto synLoop = new Object;
int numWaiters = 10;
int numTries = 10;
int numReady = 0;
int numTotal = 0;
int numDone = 0;
int numPost = 0;
void waiter()
{
for ( int i = 0; i < numTries; ++i )
{
synchronized( mutex )
{
while ( numReady < 1 )
{
condReady.wait();
}
--numReady;
++numTotal;
}
synchronized( synLoop )
{
++numDone;
}
semDone.wait();
}
}
auto group = new ThreadGroup;
for ( int i = 0; i < numWaiters; ++i )
group.create( &waiter );
for ( int i = 0; i < numTries; ++i )
{
for ( int j = 0; j < numWaiters; ++j )
{
synchronized( mutex )
{
++numReady;
condReady.notify();
}
}
while ( true )
{
synchronized( synLoop )
{
if ( numDone >= numWaiters )
break;
}
Thread.yield();
}
for ( int j = 0; j < numWaiters; ++j )
{
semDone.notify();
}
}
group.joinAll();
assert( numTotal == numWaiters * numTries );
}
void testNotifyAll()
{
auto mutex = new Mutex;
auto condReady = new Condition( mutex );
int numWaiters = 10;
int numReady = 0;
int numDone = 0;
bool alert = false;
void waiter()
{
synchronized( mutex )
{
++numReady;
while ( !alert )
condReady.wait();
++numDone;
}
}
auto group = new ThreadGroup;
for ( int i = 0; i < numWaiters; ++i )
group.create( &waiter );
while ( true )
{
synchronized( mutex )
{
if ( numReady >= numWaiters )
{
alert = true;
condReady.notifyAll();
break;
}
}
Thread.yield();
}
group.joinAll();
assert( numReady == numWaiters && numDone == numWaiters );
}
void testWaitTimeout()
{
auto mutex = new Mutex;
auto condReady = new Condition( mutex );
bool waiting = false;
bool alertedOne = true;
bool alertedTwo = true;
void waiter()
{
synchronized( mutex )
{
waiting = true;
// we never want to miss the notification (30s)
alertedOne = condReady.wait( dur!"seconds"(30) );
// but we don't want to wait long for the timeout (10ms)
alertedTwo = condReady.wait( dur!"msecs"(10) );
}
}
auto thread = new Thread( &waiter );
thread.start();
while ( true )
{
synchronized( mutex )
{
if ( waiting )
{
condReady.notify();
break;
}
}
Thread.yield();
}
thread.join();
assert( waiting );
assert( alertedOne );
assert( !alertedTwo );
}
testNotify();
testNotifyAll();
testWaitTimeout();
Condition;
import (package) corecore.(package) core.syncsync.(module) core.sync.mutexThe mutex module provides a primitive for maintaining mutually exclusive
access.
Source
core/sync/mutex.d
mutex : (class) core.sync.mutex.MutexThis class represents a general purpose, recursive mutex.
Implemented using pthread_mutex on Posix and CRITICAL_SECTION
on Windows.
Examples
import core.thread : Thread;
class Resource
{
Mutex mtx;
int cargo;
this() shared @safe nothrow
{
mtx = new shared Mutex();
cargo = 42;
}
void useResource() shared @trusted nothrow @nogc
{
mtx.lock_nothrow();
(cast() cargo) += 1;
mtx.unlock_nothrow();
}
}
shared Resource res = new shared Resource();
auto otherThread = new Thread(
{
foreach (i; 0 .. 10000)
res.useResource();
}).start();
foreach (i; 0 .. 10000)
res.useResource();
otherThread.join();
assert (res.cargo == 20042);
Mutex;
import (package) corecore.(package) core.syssys.(package) core.sys.linuxlinux.(package) core.sys.linux.syssys.(module) core.sys.linux.sys.eventfdD header file for GNU/Linux.
eventfd : (alias) handoff_latency.eventfd = int core.sys.linux.sys.eventfd.eventfd(uint count, int flags) nothrow @nogceventfd;
import (package) corecore.(package) core.syssys.(package) core.sys.linuxlinux.(module) core.sys.linux.unistdunistd : (alias) handoff_latency.syscall = long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogcInvoke system call number sysno, passing it the remaining arguments.
syscall;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.unistdD header file for POSIX.
unistd : (alias) handoff_latency.close = int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose, (alias) handoff_latency.read = long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread, (alias) handoff_latency.write = long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogcwrite;
import (package) corecore.(module) core.threadThe thread module provides support for thread creation and management.
Source
core/thread/package.d
thread : (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread;
import (package) corecore.(module) core.timeModule containing core time functionality, such as Duration (which
represents a duration of time) or MonoTime (which represents a
timestamp of the system's monotonic clock).
Various functions take a string (or strings) to represent a unit of time
(e.g. convert!("days", "hours")(numDays)). The valid strings to use
with such functions are "years", "months", "weeks", "days", "hours",
"minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds),
"hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There
are a few functions that also allow "nsecs", but very little actually
has precision greater than hnsecs.
Symbol Description Types Duration Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). TickDuration DEPRECATED Represents a duration of time in system clock ticks, using the highest precision that the system provides. MonoTime Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides. Functions convert Generic way of converting between two time units. dur Allows constructing a Duration from the given time units with the given length. weeks days hours
minutes seconds msecs
usecs hnsecs nsecs |
Convenience aliases for dur. |
| abs | Returns the absolute value of a duration. |
From Duration
From TickDuration
From units
To Duration tickDuration.to, std,conv!Duration() dur!"msecs"(5) or 5.msecs()
| To TickDuration |
duration.to, std,conv!TickDuration() |
|
TickDuration.from!"msecs"(msecs) |
| To units |
duration.total!"days" |
tickDuration.msecs |
convert!("days", "msecs")(msecs) |
Source
core/time.d
time : (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) handoff_latency.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to writef(fmt, args, '\n').
writefln;
version (X86_64X86_64)
enum long (constant) long handoff_latency.sysFutex = 202LsysFutex = 202;
else version (AArch64)
enum long sysFutex = 98;
else
static assert(0, "add this architecture's futex system call number");
enum int (constant) int handoff_latency.futexWaitPrivate = 128futexWaitPrivate = 128, (constant) int handoff_latency.futexWakePrivate = 129futexWakePrivate = 129;
enum (constant) int handoff_latency.rounds = 20000rounds = 20_000;
/// Runs `rounds` round trips: `ping` hands the turn over and waits for it
/// back; `pong` waits, then hands it back. Returns microseconds per round trip.
double double handoff_latency.measure(void delegate() ping, void delegate() pong) @systemRuns rounds round trips: ping hands the turn over and waits for it
back; pong waits, then hands it back. Returns microseconds per round trip.
measure(void delegate() (parameter) void delegate() pingping, void delegate() (parameter) void delegate() pongpong) @system
{
auto (local variable) core.thread.osthread.Thread otherother = new (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread({
foreach ((local variable) int __; 0 .. (constant) int handoff_latency.rounds = 20000rounds)
(parameter) void delegate() pongpong();
});
(local variable) core.thread.osthread.Thread otherother.core.thread.osthread.Thread core.thread.osthread.Thread.start() nothrowStarts the thread and invokes the function or delegate passed upon
construction.
In
This routine may only be called once per thread instance.
start();
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) startstart = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime;
foreach ((local variable) int __; 0 .. (constant) int handoff_latency.rounds = 20000rounds)
(parameter) void delegate() pingping();
const (local variable) const(core.time.Duration) elapsedelapsed = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime - core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeSubtracting two MonoTimes results in a Duration representing
the amount of time which elapsed between them.
The primary way that programs should time how long something takes is to
do
MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;
// How long it took.
Duration timeElapsed = after - before;
or to use a wrapper (such as a stop watch type) which does that.
Warning:
Because Duration is in hnsecs, whereas MonoTime is in system
ticks, it's usually the case that this assertion will fail
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);
This is generally fine, and by its very nature, converting from
system ticks to any type of seconds (hnsecs, nsecs, etc.) will
introduce rounding errors, but if code needs to avoid any of the
small rounding errors introduced by conversion, then it needs to use
MonoTime's ticks property and keep all calculations in ticks
rather than using Duration.
start;
(local variable) core.thread.osthread.Thread otherother.object.Throwable core.thread.osthread.Thread.join(bool rethrow = true)Waits for this thread to complete. If the thread terminated as the
result of an unhandled exception, this exception will be rethrown.
join();
return (local variable) const(core.time.Duration) elapsedelapsed.long core.time.Duration.total!"nsecs"() const pure nothrow @nogc @property @safeReturns the total number of the given units in this Duration.
So, unlike split, it does not strip out the larger units.
Examples
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
total!"nsecs" / 1000.0 / (constant) int handoff_latency.rounds = 20000rounds;
}
/// A word one thread sleeps on until another sets it.
struct (struct) handoff_latency.FutexFlagA word one thread sleeps on until another sets it.
FutexFlag
{
shared uint (field) shared(uint) handoff_latency.FutexFlag.wordword;
void void handoff_latency.FutexFlag.wait() nothrow @nogc @systemwait() @system nothrow @nogc
{
while (!uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) handoff_latency.FutexFlag.wordword))
long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogcInvoke system call number sysno, passing it the remaining arguments.
syscall((constant) long handoff_latency.sysFutex = 202LsysFutex, &(field) shared(uint) handoff_latency.FutexFlag.wordword, (constant) int handoff_latency.futexWaitPrivate = 128futexWaitPrivate, 0, null, null, 0);
void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((field) shared(uint) handoff_latency.FutexFlag.wordword, 0u);
}
void void handoff_latency.FutexFlag.post() nothrow @nogc @systempost() @system nothrow @nogc
{
void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((field) shared(uint) handoff_latency.FutexFlag.wordword, 1u);
long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogcInvoke system call number sysno, passing it the remaining arguments.
syscall((constant) long handoff_latency.sysFutex = 202LsysFutex, &(field) shared(uint) handoff_latency.FutexFlag.wordword, (constant) int handoff_latency.futexWakePrivate = 129futexWakePrivate, 1, null, null, 0);
}
}
void void D main() @systemmain() @system
{
// futex
(struct) handoff_latency.FutexFlagA word one thread sleeps on until another sets it.
FutexFlag (local variable) handoff_latency.FutexFlag toPongtoPong, (local variable) handoff_latency.FutexFlag toPingtoPing;
const (local variable) const(double) futexUsfutexUs = double handoff_latency.measure(void delegate() ping, void delegate() pong) @systemRuns rounds round trips: ping hands the turn over and waits for it
back; pong waits, then hands it back. Returns microseconds per round trip.
measure(() { (local variable) handoff_latency.FutexFlag toPongtoPong.void handoff_latency.FutexFlag.post() nothrow @nogc @systempost(); (local variable) handoff_latency.FutexFlag toPingtoPing.void handoff_latency.FutexFlag.wait() nothrow @nogc @systemwait(); },
() { (local variable) handoff_latency.FutexFlag toPongtoPong.void handoff_latency.FutexFlag.wait() nothrow @nogc @systemwait(); (local variable) handoff_latency.FutexFlag toPingtoPing.void handoff_latency.FutexFlag.post() nothrow @nogc @systempost(); });
// eventfd
const (local variable) const(int) aa = int core.sys.linux.sys.eventfd.eventfd(uint count, int flags) nothrow @nogceventfd(0, 0), (local variable) const(int) bb = int core.sys.linux.sys.eventfd.eventfd(uint count, int flags) nothrow @nogceventfd(0, 0);
scope (exit)
{
int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose((local variable) const(int) aa);
int core.sys.posix.unistd.close(int) nothrow @nogc @trustedclose((local variable) const(int) bb);
}
ulong (local variable) ulong oneone = 1, (local variable) ulong gotgot;
const (local variable) const(double) eventfdUseventfdUs = double handoff_latency.measure(void delegate() ping, void delegate() pong) @systemRuns rounds round trips: ping hands the turn over and waits for it
back; pong waits, then hands it back. Returns microseconds per round trip.
measure(() { long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogcwrite((local variable) const(int) aa, &(local variable) ulong oneone, 8); long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread((local variable) const(int) bb, &(local variable) ulong gotgot, 8); },
() { long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogcread((local variable) const(int) aa, &(local variable) ulong gotgot, 8); long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogcwrite((local variable) const(int) bb, &(local variable) ulong oneone, 8); });
// pthread condition variable
auto (local variable) core.sync.mutex.Mutex mm = new (class) core.sync.mutex.MutexThis class represents a general purpose, recursive mutex.
Implemented using pthread_mutex on Posix and CRITICAL_SECTION
on Windows.
Examples
import core.thread : Thread;
class Resource
{
Mutex mtx;
int cargo;
this() shared @safe nothrow
{
mtx = new shared Mutex();
cargo = 42;
}
void useResource() shared @trusted nothrow @nogc
{
mtx.lock_nothrow();
(cast() cargo) += 1;
mtx.unlock_nothrow();
}
}
shared Resource res = new shared Resource();
auto otherThread = new Thread(
{
foreach (i; 0 .. 10000)
res.useResource();
}).start();
foreach (i; 0 .. 10000)
res.useResource();
otherThread.join();
assert (res.cargo == 20042);
Mutex;
auto (local variable) core.sync.condition.Condition condcond = new (class) core.sync.condition.ConditionThis class represents a condition variable as conceived by C.A.R. Hoare. As
per Mesa type monitors however, "signal" has been replaced with "notify" to
indicate that control is not transferred to the waiter when a notification
is sent.
Examples
import core.sync.mutex;
import core.sync.semaphore;
import core.thread;
void testNotify()
{
auto mutex = new Mutex;
auto condReady = new Condition( mutex );
auto semDone = new Semaphore;
auto synLoop = new Object;
int numWaiters = 10;
int numTries = 10;
int numReady = 0;
int numTotal = 0;
int numDone = 0;
int numPost = 0;
void waiter()
{
for ( int i = 0; i < numTries; ++i )
{
synchronized( mutex )
{
while ( numReady < 1 )
{
condReady.wait();
}
--numReady;
++numTotal;
}
synchronized( synLoop )
{
++numDone;
}
semDone.wait();
}
}
auto group = new ThreadGroup;
for ( int i = 0; i < numWaiters; ++i )
group.create( &waiter );
for ( int i = 0; i < numTries; ++i )
{
for ( int j = 0; j < numWaiters; ++j )
{
synchronized( mutex )
{
++numReady;
condReady.notify();
}
}
while ( true )
{
synchronized( synLoop )
{
if ( numDone >= numWaiters )
break;
}
Thread.yield();
}
for ( int j = 0; j < numWaiters; ++j )
{
semDone.notify();
}
}
group.joinAll();
assert( numTotal == numWaiters * numTries );
}
void testNotifyAll()
{
auto mutex = new Mutex;
auto condReady = new Condition( mutex );
int numWaiters = 10;
int numReady = 0;
int numDone = 0;
bool alert = false;
void waiter()
{
synchronized( mutex )
{
++numReady;
while ( !alert )
condReady.wait();
++numDone;
}
}
auto group = new ThreadGroup;
for ( int i = 0; i < numWaiters; ++i )
group.create( &waiter );
while ( true )
{
synchronized( mutex )
{
if ( numReady >= numWaiters )
{
alert = true;
condReady.notifyAll();
break;
}
}
Thread.yield();
}
group.joinAll();
assert( numReady == numWaiters && numDone == numWaiters );
}
void testWaitTimeout()
{
auto mutex = new Mutex;
auto condReady = new Condition( mutex );
bool waiting = false;
bool alertedOne = true;
bool alertedTwo = true;
void waiter()
{
synchronized( mutex )
{
waiting = true;
// we never want to miss the notification (30s)
alertedOne = condReady.wait( dur!"seconds"(30) );
// but we don't want to wait long for the timeout (10ms)
alertedTwo = condReady.wait( dur!"msecs"(10) );
}
}
auto thread = new Thread( &waiter );
thread.start();
while ( true )
{
synchronized( mutex )
{
if ( waiting )
{
condReady.notify();
break;
}
}
Thread.yield();
}
thread.join();
assert( waiting );
assert( alertedOne );
assert( !alertedTwo );
}
testNotify();
testNotifyAll();
testWaitTimeout();
Condition((local variable) core.sync.mutex.Mutex mm);
bool (local variable) bool pongTurnpongTurn;
const (local variable) const(double) condUscondUs = double handoff_latency.measure(void delegate() ping, void delegate() pong) @systemRuns rounds round trips: ping hands the turn over and waits for it
back; pong waits, then hands it back. Returns microseconds per round trip.
measure(() {
(local variable) core.sync.mutex.Mutex mm.void core.sync.mutex.Mutex.lock() @trustedIf this lock is not already held by the caller, the lock is acquired,
then the internal counter is incremented by one.
Note
Mutex.lock`` does not throw, but a class derived from Mutex can throw.
Use lock_nothrow in nothrow @nogc code.
lock();
(local variable) bool pongTurnpongTurn = true;
(local variable) core.sync.condition.Condition condcond.void core.sync.condition.Condition.notifyAll()Notifies all waiters.
notifyAll();
while ((local variable) bool pongTurnpongTurn)
(local variable) core.sync.condition.Condition condcond.void core.sync.condition.Condition.wait()Wait until notified.
wait();
(local variable) core.sync.mutex.Mutex mm.void core.sync.mutex.Mutex.unlock() @trustedDecrements the internal lock count by one. If this brings the count to
zero, the lock is released.
Note
Mutex.unlock`` does not throw, but a class derived from Mutex can throw.
Use unlock_nothrow in nothrow @nogc code.
unlock();
}, () {
(local variable) core.sync.mutex.Mutex mm.void core.sync.mutex.Mutex.lock() @trustedIf this lock is not already held by the caller, the lock is acquired,
then the internal counter is incremented by one.
Note
Mutex.lock`` does not throw, but a class derived from Mutex can throw.
Use lock_nothrow in nothrow @nogc code.
lock();
while (!(local variable) bool pongTurnpongTurn)
(local variable) core.sync.condition.Condition condcond.void core.sync.condition.Condition.wait()Wait until notified.
wait();
(local variable) bool pongTurnpongTurn = false;
(local variable) core.sync.condition.Condition condcond.void core.sync.condition.Condition.notifyAll()Notifies all waiters.
notifyAll();
(local variable) core.sync.mutex.Mutex mm.void core.sync.mutex.Mutex.unlock() @trustedDecrements the internal lock count by one. If this brings the count to
zero, the lock is released.
Note
Mutex.unlock`` does not throw, but a class derived from Mutex can throw.
Use unlock_nothrow in nothrow @nogc code.
unlock();
});
void std.stdio.writefln!(char, int)(in char[] fmt, int __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln("%u round trips each; microseconds per round trip (two sleeps, two wakes)", (constant) int handoff_latency.rounds = 20000rounds);
void std.stdio.writefln!(char, string, const(double))(in char[] fmt, string __param_1, const(double) __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln(" %-14s %6.2f", "futex", (local variable) const(double) futexUsfutexUs);
void std.stdio.writefln!(char, string, const(double))(in char[] fmt, string __param_1, const(double) __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln(" %-14s %6.2f", "eventfd", (local variable) const(double) eventfdUseventfdUs);
void std.stdio.writefln!(char, string, const(double))(in char[] fmt, string __param_1, const(double) __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln(" %-14s %6.2f", "pthread cond", (local variable) const(double) condUscondUs);
}