handoff-latency.dhover×166all
#!/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_latency

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.

handoff_latency
;
version (
linux
linux
)
version =
(version) linuxBench
linuxBench
;
version (
linuxBench
linuxBench
) {} else
{ void main() { import std.stdio : writeln; writeln("SKIP: the futex and eventfd mechanisms need Linux"); } } version (
linuxBench
linuxBench
):
import
(package) core
core
.
(module) core.atomic

The 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);
@copyrightCopyright Sean Kelly 2005 - 2016.@licenseBoost License 1.0@authorsSean Kelly, Alex Rønne Petersen, Manu Evans
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.

@paramval The target variable.@returnsThe value of 'val'.
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.

@paramval The target variable.@paramnewval The value to store.
atomicStore
;
import
(package) core
core
.
(package) core.sync
sync
.
(module) core.sync.condition

The condition module provides a primitive for synchronized condition checking.

Source

core/sync/condition.d

@copyrightCopyright Sean Kelly 2005 - 2009.@licenseBoost License 1.0@authorsSean Kelly
condition
:
(class) core.sync.condition.Condition

This 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) core
core
.
(package) core.sync
sync
.
(module) core.sync.mutex

The mutex module provides a primitive for maintaining mutually exclusive access.

Source

core/sync/mutex.d

@copyrightCopyright Sean Kelly 2005 - 2009.@licenseBoost License 1.0@authorsSean Kelly
mutex
:
(class) core.sync.mutex.Mutex

This 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) core
core
.
(package) core.sys
sys
.
(package) core.sys.linux
linux
.
(package) core.sys.linux.sys
sys
.
(module) core.sys.linux.sys.eventfd

D header file for GNU/Linux.

@licenseBoost License 1.0@authorsNemanja Boric
eventfd
:
(alias) handoff_latency.eventfd = int core.sys.linux.sys.eventfd.eventfd(uint count, int flags) nothrow @nogc
eventfd
;
import
(package) core
core
.
(package) core.sys
sys
.
(package) core.sys.linux
linux
.
(module) core.sys.linux.unistd
unistd
:
(alias) handoff_latency.syscall = long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogc

Invoke system call number sysno, passing it the remaining arguments.

syscall
;
import
(package) core
core
.
(package) core.sys
sys
.
(package) core.sys.posix
posix
.
(module) core.sys.posix.unistd

D header file for POSIX.

@copyrightCopyright Sean Kelly 2005 - 2009.@licenseBoost License 1.0.@authorsSean Kelly@standardsThe Open Group Base Specifications Issue 8, IEEE Std 1003.1, 2024 Edition
unistd
:
(alias) handoff_latency.close = int core.sys.posix.unistd.close(int) nothrow @nogc @trusted
close
,
(alias) handoff_latency.read = long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogc
read
,
(alias) handoff_latency.write = long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogc
write
;
import
(package) core
core
.
(module) core.thread

The thread module provides support for thread creation and management.

Source

core/thread/package.d

@copyrightCopyright Sean Kelly 2005 - 2012.@licenseDistributed under the Boost Software License 1.0. (See accompanying file LICENSE)@authorsSean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak
thread
:
(class) core.thread.osthread.Thread

This 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) core
core
.
(module) core.time

Module 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&nbsp;days&nbsp;hours

minutes&nbsp;seconds&nbsp;msecs

usecs&nbsp;hnsecs&nbsp;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

@copyrightCopyright 2010 - 2012@licenseBoost License 1.0.@authorsJonathan M Davis and Kato Shoichi
time
:
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
;
import
(package) std
std
.
(module) std.stdio
Category 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:

  1. The lowest layer is the operating system layer. The two main schemes are Windows and Posix.

  2. C's stdio.h which unifies the two operating system schemes.

  3. std.stdio, this module, unifies the various stdio.h implementations into a high level package for D programs.

Source

std/stdio.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Alex Rønne Petersen
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_64
X86_64
)
enum long
(constant) long handoff_latency.sysFutex = 202L
sysFutex
= 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 = 128
futexWaitPrivate
= 128,
(constant) int handoff_latency.futexWakePrivate = 129
futexWakePrivate
= 129;
enum
(constant) int handoff_latency.rounds = 20000
rounds
= 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) @system

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.

measure
(void delegate()
(parameter) void delegate() ping
ping
, void delegate()
(parameter) void delegate() pong
pong
) @system
{ auto
(local variable) core.thread.osthread.Thread other
other
= new
(class) core.thread.osthread.Thread

This 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 = 20000
rounds
)
(parameter) void delegate() pong
pong
();
});
(local variable) core.thread.osthread.Thread other
other
.
core.thread.osthread.Thread core.thread.osthread.Thread.start() nothrow

Starts the thread and invokes the function or delegate passed upon construction.

In

This routine may only be called once per thread instance.

@throwsThreadException if the thread fails to start.
start
();
const
(local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) start
start
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The 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 = 20000
rounds
)
(parameter) void delegate() ping
ping
();
const
(local variable) const(core.time.Duration) elapsed
elapsed
=
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
.
core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trusted

The 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 @safe

Subtracting 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 other
other
.
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.

@paramrethrow Rethrow any unhandled exception which may have caused this thread to terminate.@throwsThreadException if the operation fails. Any exception not handled by the joined thread.@returnsAny exception not handled by this thread if rethrow = false, null otherwise.
join
();
return
(local variable) const(core.time.Duration) elapsed
elapsed
.
long core.time.Duration.total!"nsecs"() const pure nothrow @nogc @property @safe

Returns 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 = 20000
rounds
;
} /// A word one thread sleeps on until another sets it. struct
(struct) handoff_latency.FutexFlag

A word one thread sleeps on until another sets it.

FutexFlag
{ shared uint
(field) shared(uint) handoff_latency.FutexFlag.word
word
;
void
void handoff_latency.FutexFlag.wait() nothrow @nogc @system
wait
() @system nothrow @nogc
{ while (!
uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trusted

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.

@paramval The target variable.@returnsThe value of 'val'.
atomicLoad
(
(field) shared(uint) handoff_latency.FutexFlag.word
word
))
long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogc

Invoke system call number sysno, passing it the remaining arguments.

syscall
(
(constant) long handoff_latency.sysFutex = 202L
sysFutex
, &
(field) shared(uint) handoff_latency.FutexFlag.word
word
,
(constant) int handoff_latency.futexWaitPrivate = 128
futexWaitPrivate
, 0, null, null, 0);
void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trusted

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.

@paramval The target variable.@paramnewval The value to store.
atomicStore
(
(field) shared(uint) handoff_latency.FutexFlag.word
word
, 0u);
} void
void handoff_latency.FutexFlag.post() nothrow @nogc @system
post
() @system nothrow @nogc
{
void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trusted

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.

@paramval The target variable.@paramnewval The value to store.
atomicStore
(
(field) shared(uint) handoff_latency.FutexFlag.word
word
, 1u);
long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogc

Invoke system call number sysno, passing it the remaining arguments.

syscall
(
(constant) long handoff_latency.sysFutex = 202L
sysFutex
, &
(field) shared(uint) handoff_latency.FutexFlag.word
word
,
(constant) int handoff_latency.futexWakePrivate = 129
futexWakePrivate
, 1, null, null, 0);
} } void
void D main() @system
main
() @system
{ // futex
(struct) handoff_latency.FutexFlag

A word one thread sleeps on until another sets it.

FutexFlag
(local variable) handoff_latency.FutexFlag toPong
toPong
,
(local variable) handoff_latency.FutexFlag toPing
toPing
;
const
(local variable) const(double) futexUs
futexUs
=
double handoff_latency.measure(void delegate() ping, void delegate() pong) @system

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.

measure
(() {
(local variable) handoff_latency.FutexFlag toPong
toPong
.
void handoff_latency.FutexFlag.post() nothrow @nogc @system
post
();
(local variable) handoff_latency.FutexFlag toPing
toPing
.
void handoff_latency.FutexFlag.wait() nothrow @nogc @system
wait
(); },
() {
(local variable) handoff_latency.FutexFlag toPong
toPong
.
void handoff_latency.FutexFlag.wait() nothrow @nogc @system
wait
();
(local variable) handoff_latency.FutexFlag toPing
toPing
.
void handoff_latency.FutexFlag.post() nothrow @nogc @system
post
(); });
// eventfd const
(local variable) const(int) a
a
=
int core.sys.linux.sys.eventfd.eventfd(uint count, int flags) nothrow @nogc
eventfd
(0, 0),
(local variable) const(int) b
b
=
int core.sys.linux.sys.eventfd.eventfd(uint count, int flags) nothrow @nogc
eventfd
(0, 0);
scope (exit) {
int core.sys.posix.unistd.close(int) nothrow @nogc @trusted
close
(
(local variable) const(int) a
a
);
int core.sys.posix.unistd.close(int) nothrow @nogc @trusted
close
(
(local variable) const(int) b
b
);
} ulong
(local variable) ulong one
one
= 1,
(local variable) ulong got
got
;
const
(local variable) const(double) eventfdUs
eventfdUs
=
double handoff_latency.measure(void delegate() ping, void delegate() pong) @system

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.

measure
(() {
long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogc
write
(
(local variable) const(int) a
a
, &
(local variable) ulong one
one
, 8);
long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogc
read
(
(local variable) const(int) b
b
, &
(local variable) ulong got
got
, 8); },
() {
long core.sys.posix.unistd.read(int, void*, ulong) nothrow @nogc
read
(
(local variable) const(int) a
a
, &
(local variable) ulong got
got
, 8);
long core.sys.posix.unistd.write(int, scope const(void*), ulong) nothrow @nogc
write
(
(local variable) const(int) b
b
, &
(local variable) ulong one
one
, 8); });
// pthread condition variable auto
(local variable) core.sync.mutex.Mutex m
m
= new
(class) core.sync.mutex.Mutex

This 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 cond
cond
= new
(class) core.sync.condition.Condition

This 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 m
m
);
bool
(local variable) bool pongTurn
pongTurn
;
const
(local variable) const(double) condUs
condUs
=
double handoff_latency.measure(void delegate() ping, void delegate() pong) @system

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.

measure
(() {
(local variable) core.sync.mutex.Mutex m
m
.
void core.sync.mutex.Mutex.lock() @trusted

If 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 pongTurn
pongTurn
= true;
(local variable) core.sync.condition.Condition cond
cond
.
void core.sync.condition.Condition.notifyAll()

Notifies all waiters.

@throwsSyncError on error.
notifyAll
();
while (
(local variable) bool pongTurn
pongTurn
)
(local variable) core.sync.condition.Condition cond
cond
.
void core.sync.condition.Condition.wait()

Wait until notified.

@throwsSyncError on error.
wait
();
(local variable) core.sync.mutex.Mutex m
m
.
void core.sync.mutex.Mutex.unlock() @trusted

Decrements 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 m
m
.
void core.sync.mutex.Mutex.lock() @trusted

If 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 pongTurn
pongTurn
)
(local variable) core.sync.condition.Condition cond
cond
.
void core.sync.condition.Condition.wait()

Wait until notified.

@throwsSyncError on error.
wait
();
(local variable) bool pongTurn
pongTurn
= false;
(local variable) core.sync.condition.Condition cond
cond
.
void core.sync.condition.Condition.notifyAll()

Notifies all waiters.

@throwsSyncError on error.
notifyAll
();
(local variable) core.sync.mutex.Mutex m
m
.
void core.sync.mutex.Mutex.unlock() @trusted

Decrements 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) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("%u round trips each; microseconds per round trip (two sleeps, two wakes)",
(constant) int handoff_latency.rounds = 20000
rounds
);
void std.stdio.writefln!(char, string, const(double))(in char[] fmt, string __param_1, const(double) __param_2) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" %-14s %6.2f", "futex",
(local variable) const(double) futexUs
futexUs
);
void std.stdio.writefln!(char, string, const(double))(in char[] fmt, string __param_1, const(double) __param_2) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" %-14s %6.2f", "eventfd",
(local variable) const(double) eventfdUs
eventfdUs
);
void std.stdio.writefln!(char, string, const(double))(in char[] fmt, string __param_1, const(double) __param_2) @safe

Equivalent to writef(fmt, args, '\n').

writefln
(" %-14s %6.2f", "pthread cond",
(local variable) const(double) condUs
condUs
);
}