mutex-throughput.dhover×640all
#!/usr/bin/env dub
/+ dub.sdl:
    name "mutex_throughput"
    dflags "-preview=dip1000" "-preview=in"
    buildType "checked" {
        buildOptions "optimize" "inline" "debugInfo"
    }
+/
/**
Throughput and fairness of five mutex designs on this machine, for
`docs/research/fine-grained-locking/comparison.md` § (a), the mutex word.

- `futex3`: the three-state futex word (unlocked, locked, contended) of
    Drepper's "Futexes Are Tricky" `mutex3`, glibc's `lll_lock` and Rust std,
    with Rust's bounded spin of 100.
- `parking`: a two-bit lock (`LOCKED`, `PARKED`) whose waiters queue in a
    global table of buckets hashed by address, each waiter parking on its own
    futex word — Rust `parking_lot`'s `RawMutex` and its `SpinWait`, without
    the bucket's `WordLock`, table growth or fair unlock.
- `parking+desig`: the same lock plus a designated-waker bit, as in nsync's
    `MU_DESIG_WAKER` and Abseil's `kMuDesig`: an unlock wakes a waiter only if
    no woken waiter is still on its way to the lock.
- `pthread`: druntime's `core.sync.mutex.Mutex`, a `pthread_mutex_t`.
- `ttas`: a test-and-test-and-set spin lock with exponential backoff and a
    `sched_yield` after 64 rounds — the baseline that no lock should be.

Every thread runs for a fixed time, taking the lock around a short critical
section. Each cell shows lock acquisitions per microsecond; fairness, the
fewest acquisitions any one thread made as a fraction of the most; and, for
the three futex locks, the `FUTEX_WAIT` and `FUTEX_WAKE` calls per
acquisition. A plain counter incremented under the lock checks mutual
exclusion. The numbers vary between runs and machines; the shapes are the
claim:

- With the cores saturated, `parking` sleeps on nearly every acquisition and
    collapses. Its `PARKED` bit is exact, so every unlock while the queue is
    non-empty wakes a waiter, which loses the race to a running thread and
    parks again. Rust's own `parking_lot` benchmark shows the same collapse
    (see the comparison). The three-state word avoids it by forgetting: a
    barging relock stores `locked`, so most unlocks wake nobody.
- `parking+desig` keeps the exact queue and wakes at most one waiter at a
    time: it sleeps on a fraction of a percent of acquisitions and has the
    highest throughput from two threads to oversubscription.
- The spin lock's fairness collapses once threads outnumber the cores.

Linux only (raw futex system calls); elsewhere it prints `SKIP:` and exits 0.
*/
module 
(module) mutex_throughput

Throughput and fairness of five mutex designs on this machine, for docs/research/fine-grained-locking/comparison.md § (a), the mutex word.

  • futex3: the three-state futex word (unlocked, locked, contended) of Drepper's "Futexes Are Tricky" mutex3, glibc's lll_lock and Rust std, with Rust's bounded spin of 100.

  • parking: a two-bit lock (LOCKED, PARKED) whose waiters queue in a global table of buckets hashed by address, each waiter parking on its own futex word — Rust parking_lot's RawMutex and its SpinWait, without the bucket's WordLock, table growth or fair unlock.

  • parking+desig: the same lock plus a designated-waker bit, as in nsync's MU_DESIG_WAKER and Abseil's kMuDesig: an unlock wakes a waiter only if no woken waiter is still on its way to the lock.

  • pthread: druntime's core.sync.mutex.Mutex, a pthread_mutex_t.

  • ttas: a test-and-test-and-set spin lock with exponential backoff and a sched_yield after 64 rounds — the baseline that no lock should be.

Every thread runs for a fixed time, taking the lock around a short critical section. Each cell shows lock acquisitions per microsecond; fairness, the fewest acquisitions any one thread made as a fraction of the most; and, for the three futex locks, the FUTEX_WAIT and FUTEX_WAKE calls per acquisition. A plain counter incremented under the lock checks mutual exclusion. The numbers vary between runs and machines; the shapes are the claim:

  • With the cores saturated, parking sleeps on nearly every acquisition and collapses. Its PARKED bit is exact, so every unlock while the queue is non-empty wakes a waiter, which loses the race to a running thread and parks again. Rust's own parking_lot benchmark shows the same collapse (see the comparison). The three-state word avoids it by forgetting: a barging relock stores locked, so most unlocks wake nobody.

  • parking+desig keeps the exact queue and wakes at most one waiter at a time: it sleeps on a fraction of a percent of acquisitions and has the highest throughput from two threads to oversubscription.

  • The spin lock's fairness collapses once threads outnumber the cores.

Linux only (raw futex system calls); elsewhere it prints SKIP: and exits 0.

mutex_throughput
;
version (
linux
linux
)
version =
(version) futexBench
futexBench
;
version (
futexBench
futexBench
) {} else
{ void main() { import std.stdio : writeln; writeln("SKIP: the futex-based locks need Linux"); } } version (
futexBench
futexBench
):
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) mutex_throughput.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) mutex_throughput.atomicOp = core.atomic.atomicOp(string op, T, V1)(ref shared T val, V1 mod) if (__traits(compiles, mixin("*cast(T*)&val" ~ op ~ "mod")))

Performs the binary operation 'op' on val using 'mod' as the modifier.

@paramval The target variable.@parammod The modifier to apply.@returnsThe result of the operation.
atomicOp
,
(alias template) mutex_throughput.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
,
(alias template) mutex_throughput.cas = core.atomic.cas(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq)

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returnstrue if the store occurred, false if not.
cas
,
(alias) mutex_throughput.pause = void core.atomic.pause() pure nothrow @nogc @safe

Gives a hint to the processor that the calling thread is in a 'spin-wait' loop, allowing to more efficiently allocate resources.

pause
;
import
(package) core
core
.
(package) core.sys
sys
.
(package) core.sys.linux
linux
.
(module) core.sys.linux.unistd
unistd
:
(alias) mutex_throughput.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.sched

D header file for POSIX.

@copyrightCopyright Sean Kelly 2005 - 2009.@licenseBoost License 1.0.@authorsSean Kelly, Alex Rønne Petersen@standardsThe Open Group Base Specifications Issue 6, IEEE Std 1003.1, 2004 Edition
sched
:
(alias) mutex_throughput.sched_yield = int core.sys.posix.sched.sched_yield() nothrow @nogc
sched_yield
;
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 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

@copyrightCopyright 2010 - 2012@licenseBoost License 1.0.@authorsJonathan M Davis and Kato Shoichi
time
:
(struct) core.time.MonoTimeImpl!(ClockType.normal)
MonoTime
, msecs;
import
(package) std
std
.
(module) std.algorithm

This package implements generic algorithms oriented towards the processing of sequences. Sequences processed by these functions define range-based interfaces. See also Reference on ranges and tutorial on ranges.

Algorithms are categorized into the following submodules:

Submodule Functions

| Searching | all any balancedParens boyerMooreFinder canFind commonPrefix count countUntil endsWith find findAdjacent findAmong findSkip findSplit findSplitAfter findSplitBefore minCount maxCount minElement maxElement minIndex maxIndex minPos maxPos skipOver startsWith until |

| Comparison | among castSwitch clamp cmp either equal isPermutation isSameLength levenshteinDistance levenshteinDistanceAndPath max min mismatch predSwitch |

| Iteration | cache cacheBidirectional chunkBy cumulativeFold each filter filterBidirectional fold group joiner map mean permutations reduce splitWhen splitter substitute sum uniq |

| Sorting | completeSort isPartitioned isSorted isStrictlyMonotonic ordered strictlyOrdered makeIndex merge multiSort nextEvenPermutation nextPermutation nthPermutation partialSort partition partition3 schwartzSort sort topN topNCopy topNIndex |

| Set operations (setops) | cartesianProduct largestPartialIntersection largestPartialIntersectionWeighted multiwayMerge multiwayUnion setDifference setIntersection setSymmetricDifference |

| Mutation | bringToFront copy fill initializeAll move moveAll moveSome moveEmplace moveEmplaceAll moveEmplaceSome remove reverse strip stripLeft stripRight swap swapRanges uninitializedFill |

Many functions in this package are parameterized with a predicate. The predicate may be any suitable callable type (a function, a delegate, a functor, or a lambda), or a compile-time string. The string may consist of any legal D expression that uses the symbol a (for unary functions) or the symbols a and b (for binary functions). These names will NOT interfere with other homonym symbols in user code because they are evaluated in a different context. The default for all binary comparison predicates is "a == b" for unordered operations and "a < b" for ordered operations.

Example

int[] a = ...;
static bool greater(int a, int b)
{
    return a > b;
}
sort!greater(a);           // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a);           // predicate as string
                           // (no ambiguity with array name)
sort(a);                   // no predicate, "a < b" is implicit

Source

std/algorithm/package.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
algorithm
:
(alias template) mutex_throughput.maxElement = std.algorithm.searching.maxElement(alias map = (a) => a, Range)(Range r) if (isInputRange!Range && !isInfinite!Range)

Iterates the passed range and returns the maximal element. A custom mapping function can be passed to map. In other languages this is sometimes called argmax.

Complexity

O(n) Exactly n - 1 comparisons are needed.

Precondition

If a seed is not given, r must not be empty.

Note

If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.

@parammap custom accessor for the comparison key@paramr range from which the maximum element will be selected@paramseed custom seed to use as initial element@returnsThe maximal element of the passed-in range.@seeextrema, minElement, max, maxCount, maxIndex, maxPos
maxElement
,
(alias template) mutex_throughput.minElement = std.algorithm.searching.minElement(alias map = (a) => a, Range)(Range r) if (isInputRange!Range && !isInfinite!Range)

Iterates the passed range and returns the minimal element. A custom mapping function can be passed to map. In other languages this is sometimes called argmin.

Complexity

O(n) Exactly n - 1 comparisons are needed.

Precondition

If a seed is not given, r must not be empty.

Note

If at least one of the arguments is NaN, the result is an unspecified value.

If you want to ignore NaNs, you can use filter and isNaN to remove them, before applying minElement. Add a suitable seed, to avoid error messages if all elements are NaNs:

<range>.filter!(a=>!a.isNaN).minElement(<seed>);

If you want to get NaN as a result if a NaN is present in the range, you can use fold and isNaN:

<range>.fold!((a,b)=>a.isNaN || b.isNaN ? real.nan : a < b ? a : b);
@parammap custom accessor for the comparison key@paramr range from which the minimal element will be selected@paramseed custom seed to use as initial element@returnsThe minimal element of the passed-in range.@seeextrema, maxElement, min, minCount, minIndex, minPos
minElement
,
(alias template) mutex_throughput.sum = std.algorithm.iteration.sum(R)(R r) if (isInputRange!R && !isInfinite!R && is(typeof(r.front + r.front)))

Sums elements of r, which must be a finite input range. Although conceptually sum`(r)` is equivalent to `fold`!((a, b) => a + b)(r, 0), sum`` uses specialized algorithms to maximize accuracy, as follows.

  • If ElementType!R is a floating-point type and R is a random-access range with length and slicing, then sum uses the pairwise summation algorithm.

  • If ElementType!R is a floating-point type and R is a finite input range (but not a random-access range with slicing), then sum uses the Kahan summation algorithm.

  • In all other cases, a simple element by element addition is done.

For floating point inputs, calculations are made in spec/type, Types, real precision for real inputs and in double precision otherwise (Note this is a special case that deviates from fold's behavior, which would have kept float precision for a float range). For all other types, the calculations are done in the same type obtained from from adding two elements of the range, which may be a different type from the elements themselves (for example, in case of integral promotion).

A seed may be passed to sum. Not only will this seed be used as an initial value, but its type will override all the above, and determine the algorithm and precision used for summation. If a seed is not passed, one is created with the value of typeof(r.front + r.front)(0), or typeof(r.front + r.front).zero if no constructor exists that takes an int.

Note that these specialized summing algorithms execute more primitive operations than vanilla summation. Therefore, if in certain cases maximum speed is required at expense of precision, one can use fold!((a, b) => a + b)(r, 0), which is not specialized for summation.

@paramseed the initial value of the summation@paramr a finite input range@returnsThe sum of all the elements in the range r.
sum
;
import
(package) std
std
.
(module) std.format

This package provides string formatting functionality using printf style format strings.

Submodule Function Name Description
package
format
Converts its arguments according to a format string into a string.

| package | sformat | Converts its arguments according to a format string into a buffer. |

| package | FormatException | Signals a problem while formatting. |

| write | formattedWrite | Converts its arguments according to a format string and writes the result to an output range. |

| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |

| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |

| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |

| spec | FormatSpec | A general handler for format strings. |

| spec | singleSpec | Helper function that returns a FormatSpec for a single format specifier. |

Limitation

This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more parameters and ends with a format indicator. A format indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar:

FormatString: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator

FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter

Parameters: Position Flags Width Precision Separator Position: empty Integer '$'** *Integer* **':'** *Integer* **'$' Integer ':' '$'** *Flags*: *empty* *Flag* *Flags* *Flag*: **'-'**|**'+'**|**'&nbsp;'**|**'0'**|**'#'**|**'='** *Width*: *OptionalPositionalInteger* *Precision*: *empty* **'.'** *OptionalPositionalInteger* *Separator*: *empty* **','** *OptionalInteger* **','** *OptionalInteger* **'?'** *OptionalInteger*: *empty* *Integer* **'*'** *OptionalPositionalInteger*: *OptionalInteger* **'*'** *Integer* **'$'

Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note

The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

FormatCharacter Semantics
's'
To be formatted in a human readable format.
Can be used with all types.
'c'
To be formatted as a character.
'd'
To be formatted as a signed decimal integer.
'u'
To be formatted as a decimal image of the underlying bit representation.
'b'
To be formatted as a binary image of the underlying bit representation.
'o'
To be formatted as an octal image of the underlying bit representation.
'x' / 'X'
To be formatted as a hexadecimal image of the underlying bit representation.
'e' / 'E'
To be formatted as a real number in decimal scientific notation.
'f' / 'F'
To be formatted as a real number in decimal natural notation.
'g' / 'G'
To be formatted as a real number in decimal short notation.
Depending on the number, a scientific notation or
a natural notation is used.
'a' / 'A'
To be formatted as a real number in hexadecimal scientific notation.
'r'
To be formatted as raw bytes.
The output may not be printable and depends on endianness.

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note

Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Flag Semantics
'-'
When the formatted result is shorter than the value
given by the width parameter, the output is left
justified. Without the '-' flag, the output remains
right justified.

There are two exceptions where the '-' flag has a different meaning: (1) with 'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. | | '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if '-' flag is present in addition to the '=' flag, it is moved slightly to the left. | | '+'&nbsp;/&nbsp;*'&nbsp;'* | Applies to numerical values. By default, positive numbers are not formatted to include the + sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used.

In case of 'r', a big endian format is used. | | '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. | | '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and the format character used. See the sections below for more information. |

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a ''* after the ','.

In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and separator parameters are considered unspecified. For width, the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.

  • Rounding of floating point numbers adheres to the rounding mode of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals. All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more detailed information.

This table contains descriptions for every possible combination of type and format character:

<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as...
<td rowspan="1">null</td> 's'
null

|<td rowspan="3">bool</td> 's' | false or true |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integrals 0 or 1 with the same format character.

Please note, that 'o' and 'x' with '#' flag might produce unexpected results due to special handling of the value 0. |

| 'r' | \0 or \1 |

|<td rowspan="4">Integral</td> 's', 'd' | A signed decimal number. The '#' flag is ignored. |

| 'b', 'o', 'u', 'x', 'X' | An unsigned binary, decimal, octal or hexadecimal number.

In case of 'o' and 'x', the '#' flag denotes that the number must be preceded by 0 and 0x, with the exception of the value 0, where this does not apply. For 'b' and 'u' the '#' flag has no effect. |

| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' | As a floating point value with the same specifier.

Default precision is large enough to add all digits of the integral value.

In case of 'a' and 'A', the integral digit can be any hexadecimal digit. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="5">Floating Point</td> 'e', 'E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as 'e' followed by a '+' or '-' sign, followed by at least two digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'f', 'F' | Natural notation: Integral digits followed by a dot and fractional digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted.

Please note: the difference between 'f' and 'F' is only visible for NaN and Infinity. |

| 's', 'g', 'G' | Short notation: If the absolute value is larger than 10 ^^ precision or smaller than 0.0001, the scientific notation is used. If not, the natural notation is applied.

In both cases precision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed.

If '#' flag is present, trailing zeros are not removed. |

| 'a', 'A' | Hexadecimal scientific notation: 0x followed by 1 (or 0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build by p, followed by a sign and the exponent in decimal notation.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">Character</td> 's', 'c' | As the character.

Inside of a compound indicator 's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integral that represents the character. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">String</td> 's' | The sequence of characters that form the string.

Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'r' | The sequence of characters, each formatted with 'r'. |

| compound | As an array of characters. |

|<td rowspan="3">Array</td> 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="2">Associative Array</td> 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted as key:value. |

| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example "%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. |

|<td rowspan="2">Enum</td> 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |

| All, but 's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. |

|<td rowspan="3">Input Range</td> 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Struct</td> 's' | When the struct has neither an applicable toString nor is an input range, it is formatted as follows: StructType(field1, field2, ...). |

|<td rowspan="1">Class</td> 's' | When the class has neither an applicable toString nor is an input range, it is formatted as the fully qualified name of the class. |

|<td rowspan="1">Union</td> 's' | When the union has neither an applicable toString nor is an input range, it is formatted as its base name. |

|<td rowspan="2">Pointer</td> 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character 'X'. |

| 'x', 'X' | Formatted as a hexadecimal number. |

|<td rowspan="3">SIMD vector</td> 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Delegate</td> 's', 'r', compound | As the .stringof of this delegate treated as a string.

Please note: The implementation is currently buggy and its use is discouraged. |

Source

std/format/package.d

Examples

Simple use:

// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");

// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");

Compound specifiers allow formatting arrays and other compound types:

/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
 */
    assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
    assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");

/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
 */
    assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");

/*
These compound format specifiers may be nested in the case of a
nested array argument:
 */
    auto mat = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]];

    assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
    assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
    assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");

/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
 */
    assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
    assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
    assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);

Using parameters:

// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");

// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == ">   1234.57<");

// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");

// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");

Providing parameters as arguments:

// Width as argument
assert(format(">%*s<", 10, "abc") == ">       abc<");

// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");

// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");

// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");

// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == "   000/002147/483647");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) mutex_throughput.format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)

Converts its arguments according to a format string into a string.

The second version of format takes the format string as template argument. In this case, it is checked for consistency at compile-time and produces slightly faster code, because the length of the output buffer can be estimated in advance.

@paramfmt a format string@paramargs a variadic list of arguments to be formatted@paramChar character type of fmt@paramArgs a variadic list of types of the arguments@returnsThe formatted string.@throwsA FormatException if formatting did not succeed.@seesformat for a variant, that tries to avoid garbage collection.
format
;
import
(package) std
std
.
(module) std.parallelism

std.parallelism implements high-level primitives for SMP `parallelism`. These include parallel foreach, parallel reduce, parallel eager map, pipelining and future/promise `parallelism`. `std.`parallelism is recommended when the same operation is to be executed in parallel on different data, or when a function is to be executed in a background thread and its result returned to a well-defined main thread. For communication between arbitrary threads, see std.concurrency.

std.parallelism`` is based on the concept of a Task. A Task is an object that represents the fundamental unit of work in this library and may be executed in parallel with any other Task. Using Task directly allows programming with a future/promise paradigm. All other supported parallelism paradigms (parallel foreach, map, reduce, pipelining) represent an additional level of abstraction over Task. They automatically create one or more Task objects, or closely related types that are conceptually identical but not part of the public API.

After creation, a Task may be executed in a new thread, or submitted to a TaskPool for execution. A TaskPool encapsulates a task queue and its worker threads. Its purpose is to efficiently map a large number of Tasks onto a smaller number of threads. A task queue is a FIFO queue of Task objects that have been submitted to the TaskPool and are awaiting execution. A worker thread is a thread that is associated with exactly one task queue. It executes the Task at the front of its queue when the queue has work available, or sleeps when no work is available. Each task queue is associated with zero or more worker threads. If the result of a Task is needed before execution by a worker thread has begun, the Task can be removed from the task queue and executed immediately in the thread where the result is needed.

Warning

Unless marked as @trusted or @safe, artifacts in this module allow implicit data sharing between threads and cannot guarantee that client code is free from low level data races.

Source

std/parallelism.d

Author

David Simcha

@copyrightCopyright (c) 2009-2011, David Simcha.@licenseBoost License 1.0
parallelism
: totalCPUs;
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) mutex_throughput.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))

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

writefln
,
(alias template) mutex_throughput.writeln = std.stdio.writeln(T...)(T args)

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
;
version (
X86_64
X86_64
)
enum long
(constant) long mutex_throughput.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 mutex_throughput.futexWaitPrivate = 128
futexWaitPrivate
= 128,
(constant) int mutex_throughput.futexWakePrivate = 129
futexWakePrivate
= 129;
/// Wait and wake system calls made by this thread, so the table can show them /// per acquisition. Thread-local: counting must not add contention. ulong
(thread local global) ulong mutex_throughput.wakeCalls

Wait and wake system calls made by this thread, so the table can show them per acquisition. Thread-local: counting must not add contention.

wakeCalls
,
(thread local global) ulong mutex_throughput.waitCalls

Wait and wake system calls made by this thread, so the table can show them per acquisition. Thread-local: counting must not add contention.

waitCalls
;
void
void mutex_throughput.futexWait(shared(uint)* word, uint expected) nothrow @nogc @system
futexWait
(shared(uint)*
(parameter) shared(uint)* word
word
, uint
(parameter) uint expected
expected
) @system nothrow @nogc
{ ++
(thread local global) ulong mutex_throughput.waitCalls

Wait and wake system calls made by this thread, so the table can show them per acquisition. Thread-local: counting must not add contention.

waitCalls
;
long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogc

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

syscall
(
(constant) long mutex_throughput.sysFutex = 202L
sysFutex
,
(parameter) shared(uint)* word
word
,
(constant) int mutex_throughput.futexWaitPrivate = 128
futexWaitPrivate
,
(parameter) uint expected
expected
, null, null, 0);
} void
void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @system
futexWake
(shared(uint)*
(parameter) shared(uint)* word
word
, int
(parameter) int count
count
) @system nothrow @nogc
{ ++
(thread local global) ulong mutex_throughput.wakeCalls

Wait and wake system calls made by this thread, so the table can show them per acquisition. Thread-local: counting must not add contention.

wakeCalls
;
long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogc

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

syscall
(
(constant) long mutex_throughput.sysFutex = 202L
sysFutex
,
(parameter) shared(uint)* word
word
,
(constant) int mutex_throughput.futexWakePrivate = 129
futexWakePrivate
,
(parameter) int count
count
, null, null, 0);
} /// The three-state futex mutex. struct
(struct) mutex_throughput.Futex3

The three-state futex mutex.

Futex3
{ enum uint
(constant) uint mutex_throughput.Futex3.unlocked = 0u
unlocked
= 0,
(constant) uint mutex_throughput.Futex3.locked = 1u
locked
= 1,
(constant) uint mutex_throughput.Futex3.contended = 2u
contended
= 2;
shared uint
(field) shared(uint) mutex_throughput.Futex3.state
state
;
void
void mutex_throughput.Futex3.lock() nothrow @nogc @system
lock
() @system nothrow @nogc
{ if (
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Futex3.state
state
,
(constant) uint mutex_throughput.Futex3.unlocked = 0u
unlocked
,
(constant) uint mutex_throughput.Futex3.locked = 1u
locked
))
return; // Spin while the lock is held but nobody waits (Rust std: 100). foreach (
(local variable) int _
_
; 0 .. 100)
{ const
(local variable) const(uint) s
s
=
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) mutex_throughput.Futex3.state
state
);
if (
(local variable) const(uint) s
s
==
(constant) uint mutex_throughput.Futex3.unlocked = 0u
unlocked
&&
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Futex3.state
state
,
(constant) uint mutex_throughput.Futex3.unlocked = 0u
unlocked
,
(constant) uint mutex_throughput.Futex3.locked = 1u
locked
))
return; if (
(local variable) const(uint) s
s
==
(constant) uint mutex_throughput.Futex3.contended = 2u
contended
)
break;
void core.atomic.pause() pure nothrow @nogc @safe

Gives a hint to the processor that the calling thread is in a 'spin-wait' loop, allowing to more efficiently allocate resources.

pause
();
} // Mark it contended; whoever unlocks will wake one waiter. while (
uint mutex_throughput.atomicExchange(shared(uint)* p, uint v) nothrow @nogc @system
atomicExchange
(&
(field) shared(uint) mutex_throughput.Futex3.state
state
,
(constant) uint mutex_throughput.Futex3.contended = 2u
contended
) !=
(constant) uint mutex_throughput.Futex3.unlocked = 0u
unlocked
)
void mutex_throughput.futexWait(shared(uint)* word, uint expected) nothrow @nogc @system
futexWait
(&
(field) shared(uint) mutex_throughput.Futex3.state
state
,
(constant) uint mutex_throughput.Futex3.contended = 2u
contended
);
} void
void mutex_throughput.Futex3.unlock() nothrow @nogc @system
unlock
() @system nothrow @nogc
{ if (
uint mutex_throughput.atomicExchange(shared(uint)* p, uint v) nothrow @nogc @system
atomicExchange
(&
(field) shared(uint) mutex_throughput.Futex3.state
state
,
(constant) uint mutex_throughput.Futex3.unlocked = 0u
unlocked
) ==
(constant) uint mutex_throughput.Futex3.contended = 2u
contended
)
void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @system
futexWake
(&
(field) shared(uint) mutex_throughput.Futex3.state
state
, 1);
} } uint
uint mutex_throughput.atomicExchange(shared(uint)* p, uint v) nothrow @nogc @system
atomicExchange
(shared(uint)*
(parameter) shared(uint)* p
p
, uint
(parameter) uint v
v
) @system nothrow @nogc
{ 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) atomicExchange = core.atomic.atomicExchange(MemoryOrder ms = MemoryOrder.seq, T, V)(T* here, V exchangeWith) if (!is(T == shared) && !is(V == shared))

Exchange exchangeWith with the memory referenced by here. This operation is both lock-free and atomic.

Params: here = The address of the destination variable. exchangeWith = The value to exchange.

Returns: The value held previously by here.

atomicExchange
;
return
uint core.atomic.atomicExchange!(MemoryOrder.seq, uint, uint)(shared(uint)* here, uint exchangeWith) pure nothrow @nogc @trusted

Exchange exchangeWith with the memory referenced by here. This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramexchangeWith The value to exchange.@returnsThe value held previously by here.
atomicExchange
(
(parameter) shared(uint)* p
p
,
(parameter) uint v
v
);
} /// One parked thread's record, in the waiting thread's own storage. struct
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
{ const(void)*
(field) const(void)* mutex_throughput.Waiter.key
key
;
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
*
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
;
shared uint
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
;
} /// A bucket of the global wait-queue table: a spin lock and a FIFO. struct
(struct) mutex_throughput.Bucket

A bucket of the global wait-queue table: a spin lock and a FIFO.

Bucket
{ shared uint
(field) shared(uint) mutex_throughput.Bucket.guard
guard
;
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
*
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.head
head
,
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
;
ubyte[64 - uint.
(constant) ulong uint.sizeof = 4LU
sizeof
- 2 * (
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
*).
(constant) ulong mutex_throughput.Waiter*.sizeof = 8LU
sizeof
]
(field) ubyte[44] mutex_throughput.Bucket.pad
pad
;
void
void mutex_throughput.Bucket.acquire() nothrow @nogc @system
acquire
() @system nothrow @nogc
{ // Test and test-and-set: spin on a load, so waiters do not steal the // line from the holder. 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) mutex_throughput.Bucket.guard
guard
) || !
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Bucket.guard
guard
, 0u, 1u))
void core.atomic.pause() pure nothrow @nogc @safe

Gives a hint to the processor that the calling thread is in a 'spin-wait' loop, allowing to more efficiently allocate resources.

pause
();
} void
void mutex_throughput.Bucket.release() nothrow @nogc @system
release
() @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) mutex_throughput.Bucket.guard
guard
, 0u);
} __gshared
(struct) mutex_throughput.Bucket

A bucket of the global wait-queue table: a spin lock and a FIFO.

Bucket
[256]
(__gshared global) mutex_throughput.Bucket[256] mutex_throughput.table
table
;
ref
(struct) mutex_throughput.Bucket

A bucket of the global wait-queue table: a spin lock and a FIFO.

Bucket
mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @system
bucketOf
(const(void)*
(parameter) const(void)* key
key
) @system nothrow @nogc
{ // Fibonacci hashing of the address. const
(local variable) const(ulong) h
h
= (cast(
(alias) object.size_t = ulong
size_t
)
(parameter) const(void)* key
key
* 0x9E3779B97F4A7C15UL) >> (
(ulong) ulong
size_t
.
(constant) ulong ulong.sizeof = 8LU
sizeof
* 8 - 8);
return
(__gshared global) mutex_throughput.Bucket[256] mutex_throughput.table
table
[
(local variable) const(ulong) h
h
];
} /// The one-byte parking-lot mutex (held in a `uint` only for `cas`). struct
(struct) mutex_throughput.Parking

The one-byte parking-lot mutex (held in a uint only for cas).

Parking
{ enum uint
(constant) uint mutex_throughput.Parking.lockedBit = 1u
lockedBit
= 1,
(constant) uint mutex_throughput.Parking.parkedBit = 2u
parkedBit
= 2;
shared uint
(field) shared(uint) mutex_throughput.Parking.state
state
;
void
void mutex_throughput.Parking.lock() nothrow @nogc @system
lock
() @system nothrow @nogc
{ if (
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Parking.state
state
, 0u,
(constant) uint mutex_throughput.Parking.lockedBit = 1u
lockedBit
))
return;
void mutex_throughput.Parking.lockSlow() nothrow @nogc @system
lockSlow
();
} void
void mutex_throughput.Parking.lockSlow() nothrow @nogc @system
lockSlow
() @system nothrow @nogc
{ uint
(local variable) uint spins
spins
;
while (true) { auto
(local variable) uint s
s
=
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) mutex_throughput.Parking.state
state
);
if (!(
(local variable) uint s
s
&
(constant) uint mutex_throughput.Parking.lockedBit = 1u
lockedBit
))
{ if (
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Parking.state
state
,
(local variable) uint s
s
,
(local variable) uint s
s
|
(constant) uint mutex_throughput.Parking.lockedBit = 1u
lockedBit
))
return; continue; } // Spin while nobody is parked: parking_lot's `SpinWait`, three rounds // of 2, 4 and 8 pauses, then yields, ten rounds in all. if (!(
(local variable) uint s
s
&
(constant) uint mutex_throughput.Parking.parkedBit = 2u
parkedBit
) &&
(local variable) uint spins
spins
< 10)
{ ++
(local variable) uint spins
spins
;
if (
(local variable) uint spins
spins
<= 3)
foreach (
(local variable) int _
_
; 0 .. 1 <<
(local variable) uint spins
spins
)
void core.atomic.pause() pure nothrow @nogc @safe

Gives a hint to the processor that the calling thread is in a 'spin-wait' loop, allowing to more efficiently allocate resources.

pause
();
else
int core.sys.posix.sched.sched_yield() nothrow @nogc
sched_yield
();
continue; } if (!(
(local variable) uint s
s
&
(constant) uint mutex_throughput.Parking.parkedBit = 2u
parkedBit
) && !
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Parking.state
state
,
(local variable) uint s
s
,
(local variable) uint s
s
|
(constant) uint mutex_throughput.Parking.parkedBit = 2u
parkedBit
))
continue; // Park: validate under the bucket lock, enqueue, sleep.
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
(local variable) mutex_throughput.Waiter me
me
;
(local variable) mutex_throughput.Waiter me
me
.
(field) const(void)* mutex_throughput.Waiter.key
key
= &this;
auto
(local variable) mutex_throughput.Bucket* b
b
= &
mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @system
bucketOf
(&this);
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.acquire() nothrow @nogc @system
acquire
();
if (
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) mutex_throughput.Parking.state
state
) != (
(constant) uint mutex_throughput.Parking.lockedBit = 1u
lockedBit
|
(constant) uint mutex_throughput.Parking.parkedBit = 2u
parkedBit
))
{
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.release() nothrow @nogc @system
release
();
continue; } if (
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
)
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
= &
(local variable) mutex_throughput.Waiter me
me
;
else
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.head
head
= &
(local variable) mutex_throughput.Waiter me
me
;
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
= &
(local variable) mutex_throughput.Waiter me
me
;
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.release() nothrow @nogc @system
release
();
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
(
(local variable) mutex_throughput.Waiter me
me
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
))
void mutex_throughput.futexWait(shared(uint)* word, uint expected) nothrow @nogc @system
futexWait
(&
(local variable) mutex_throughput.Waiter me
me
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
, 0);
(local variable) uint spins
spins
= 0;
} } void
void mutex_throughput.Parking.unlock() nothrow @nogc @system
unlock
() @system nothrow @nogc
{ if (
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Parking.state
state
,
(constant) uint mutex_throughput.Parking.lockedBit = 1u
lockedBit
, 0u))
return; // Someone is parked: dequeue the first waiter for this lock. auto
(local variable) mutex_throughput.Bucket* b
b
= &
mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @system
bucketOf
(&this);
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.acquire() nothrow @nogc @system
acquire
();
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
*
(local variable) mutex_throughput.Waiter* prev
prev
,
(local variable) mutex_throughput.Waiter* w
w
=
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.head
head
;
while (
(local variable) mutex_throughput.Waiter* w
w
&&
(local variable) mutex_throughput.Waiter* w
w
.
(field) const(void)* mutex_throughput.Waiter.key
key
!is &this)
{
(local variable) mutex_throughput.Waiter* prev
prev
=
(local variable) mutex_throughput.Waiter* w
w
;
(local variable) mutex_throughput.Waiter* w
w
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
;
} bool
(local variable) bool more
more
;
if (
(local variable) mutex_throughput.Waiter* w
w
)
{ if (
(local variable) mutex_throughput.Waiter* prev
prev
)
(local variable) mutex_throughput.Waiter* prev
prev
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
;
else
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.head
head
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
;
if (
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
is
(local variable) mutex_throughput.Waiter* w
w
)
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
=
(local variable) mutex_throughput.Waiter* prev
prev
;
for (auto
(local variable) mutex_throughput.Waiter* o
o
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
; o; o = o.next)
if (
(local variable) mutex_throughput.Waiter* o
o
.
(field) const(void)* mutex_throughput.Waiter.key
key
is &this)
{
(local variable) bool more
more
= true;
break; } } // Release, keeping PARKED while others still wait (no handoff: barging).
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) mutex_throughput.Parking.state
state
,
(local variable) bool more
more
?
(constant) uint mutex_throughput.Parking.parkedBit = 2u
parkedBit
: 0u);
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.release() nothrow @nogc @system
release
();
if (
(local variable) mutex_throughput.Waiter* w
w
)
{
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
(
(local variable) mutex_throughput.Waiter* w
w
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
, 1u);
void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @system
futexWake
(&
(local variable) mutex_throughput.Waiter* w
w
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
, 1);
} } } /// The parking lock plus a designated-waker bit (nsync `MU_DESIG_WAKER`, Abseil /// `kMuDesig`): at most one woken-but-not-running waiter per lock. struct
(struct) mutex_throughput.ParkingDesig

The parking lock plus a designated-waker bit (nsync MU_DESIG_WAKER, Abseil kMuDesig): at most one woken-but-not-running waiter per lock.

ParkingDesig
{ enum uint
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
= 1,
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
= 2,
(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4u
wokenBit
= 4;
shared uint
(field) shared(uint) mutex_throughput.ParkingDesig.state
state
;
void
void mutex_throughput.ParkingDesig.lock() nothrow @nogc @system
lock
() @system nothrow @nogc
{ if (
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.ParkingDesig.state
state
, 0u,
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
))
return;
void mutex_throughput.ParkingDesig.lockSlow() nothrow @nogc @system
lockSlow
();
} void
void mutex_throughput.ParkingDesig.lockSlow() nothrow @nogc @system
lockSlow
() @system nothrow @nogc
{ uint
(local variable) uint spins
spins
;
bool
(local variable) bool designated
designated
;
while (true) { auto
(local variable) uint s
s
=
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) mutex_throughput.ParkingDesig.state
state
);
if (!(
(local variable) uint s
s
&
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
))
{ const
(local variable) const(uint) next
next
= (
(local variable) uint s
s
|
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
) & (
(local variable) bool designated
designated
? ~
(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4u
wokenBit
: ~0u);
if (
bool core.atomic.cas!().cas!(uint, uint, const(uint))(shared(uint)* here, uint ifThis, const(uint) writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.ParkingDesig.state
state
,
(local variable) uint s
s
,
(local variable) const(uint) next
next
))
return; continue; } if (!(
(local variable) uint s
s
&
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
) &&
(local variable) uint spins
spins
< 10)
{ ++
(local variable) uint spins
spins
;
if (
(local variable) uint spins
spins
<= 3)
foreach (
(local variable) int _
_
; 0 .. 1 <<
(local variable) uint spins
spins
)
void core.atomic.pause() pure nothrow @nogc @safe

Gives a hint to the processor that the calling thread is in a 'spin-wait' loop, allowing to more efficiently allocate resources.

pause
();
else
int core.sys.posix.sched.sched_yield() nothrow @nogc
sched_yield
();
continue; } // About to sleep again: give up the designation first. if (
(local variable) bool designated
designated
)
{ if (!
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.ParkingDesig.state
state
,
(local variable) uint s
s
,
(local variable) uint s
s
& ~
(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4u
wokenBit
))
continue;
(local variable) bool designated
designated
= false;
(local variable) uint s
s
&= ~
(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4u
wokenBit
;
} if (!(
(local variable) uint s
s
&
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
) && !
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.ParkingDesig.state
state
,
(local variable) uint s
s
,
(local variable) uint s
s
|
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
))
continue;
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
(local variable) mutex_throughput.Waiter me
me
;
(local variable) mutex_throughput.Waiter me
me
.
(field) const(void)* mutex_throughput.Waiter.key
key
= &this;
auto
(local variable) mutex_throughput.Bucket* b
b
= &
mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @system
bucketOf
(&this);
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.acquire() nothrow @nogc @system
acquire
();
const
(local variable) const(uint) v
v
=
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) mutex_throughput.ParkingDesig.state
state
);
if ((
(local variable) const(uint) v
v
& (
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
|
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
)) != (
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
|
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
))
{
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.release() nothrow @nogc @system
release
();
continue; } if (
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
)
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
= &
(local variable) mutex_throughput.Waiter me
me
;
else
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.head
head
= &
(local variable) mutex_throughput.Waiter me
me
;
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
= &
(local variable) mutex_throughput.Waiter me
me
;
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.release() nothrow @nogc @system
release
();
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
(
(local variable) mutex_throughput.Waiter me
me
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
))
void mutex_throughput.futexWait(shared(uint)* word, uint expected) nothrow @nogc @system
futexWait
(&
(local variable) mutex_throughput.Waiter me
me
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
, 0);
(local variable) bool designated
designated
= true;
(local variable) uint spins
spins
= 0;
} } void
void mutex_throughput.ParkingDesig.unlock() nothrow @nogc @system
unlock
() @system nothrow @nogc
{ if (
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.ParkingDesig.state
state
,
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
, 0u))
return; while (true) { const
(local variable) const(uint) s
s
=
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) mutex_throughput.ParkingDesig.state
state
);
// A designated waker is already on its way: just release. if ((
(local variable) const(uint) s
s
&
(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4u
wokenBit
) || !(
(local variable) const(uint) s
s
&
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
))
{ if (
bool core.atomic.cas!().cas!(uint, const(uint), uint)(shared(uint)* here, const(uint) ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.ParkingDesig.state
state
,
(local variable) const(uint) s
s
,
(local variable) const(uint) s
s
& ~
(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1u
lockedBit
))
return; continue; } break; } auto
(local variable) mutex_throughput.Bucket* b
b
= &
mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @system
bucketOf
(&this);
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.acquire() nothrow @nogc @system
acquire
();
(struct) mutex_throughput.Waiter

One parked thread's record, in the waiting thread's own storage.

Waiter
*
(local variable) mutex_throughput.Waiter* prev
prev
,
(local variable) mutex_throughput.Waiter* w
w
=
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.head
head
;
while (
(local variable) mutex_throughput.Waiter* w
w
&&
(local variable) mutex_throughput.Waiter* w
w
.
(field) const(void)* mutex_throughput.Waiter.key
key
!is &this)
{
(local variable) mutex_throughput.Waiter* prev
prev
=
(local variable) mutex_throughput.Waiter* w
w
;
(local variable) mutex_throughput.Waiter* w
w
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
;
} bool
(local variable) bool more
more
;
if (
(local variable) mutex_throughput.Waiter* w
w
)
{ if (
(local variable) mutex_throughput.Waiter* prev
prev
)
(local variable) mutex_throughput.Waiter* prev
prev
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
;
else
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.head
head
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
;
if (
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
is
(local variable) mutex_throughput.Waiter* w
w
)
(local variable) mutex_throughput.Bucket* b
b
.
(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tail
tail
=
(local variable) mutex_throughput.Waiter* prev
prev
;
for (auto
(local variable) mutex_throughput.Waiter* o
o
=
(local variable) mutex_throughput.Waiter* w
w
.
(field) mutex_throughput.Waiter* mutex_throughput.Waiter.next
next
; o; o = o.next)
if (
(local variable) mutex_throughput.Waiter* o
o
.
(field) const(void)* mutex_throughput.Waiter.key
key
is &this)
{
(local variable) bool more
more
= true;
break; } }
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) mutex_throughput.ParkingDesig.state
state
, (
(local variable) bool more
more
?
(constant) uint mutex_throughput.ParkingDesig.parkedBit = 2u
parkedBit
: 0u) | (
(local variable) mutex_throughput.Waiter* w
w
?
(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4u
wokenBit
: 0u));
(local variable) mutex_throughput.Bucket* b
b
.
void mutex_throughput.Bucket.release() nothrow @nogc @system
release
();
if (
(local variable) mutex_throughput.Waiter* w
w
)
{
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
(
(local variable) mutex_throughput.Waiter* w
w
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
, 1u);
void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @system
futexWake
(&
(local variable) mutex_throughput.Waiter* w
w
.
(field) shared(uint) mutex_throughput.Waiter.unparked
unparked
, 1);
} } } /// druntime's mutex, a `pthread_mutex_t`. struct
(struct) mutex_throughput.Pthread

druntime's mutex, a pthread_mutex_t.

Pthread
{ 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
;
__gshared
(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
(__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.m
m
;
void
void mutex_throughput.Pthread.lock() nothrow @nogc @system
lock
() @system nothrow @nogc =>
(__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.m
m
.
void core.sync.mutex.Mutex.lock_nothrow!(core.sync.mutex.Mutex)() nothrow @nogc @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_nothrow
();
void
void mutex_throughput.Pthread.unlock() nothrow @nogc @system
unlock
() @system nothrow @nogc =>
(__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.m
m
.
void core.sync.mutex.Mutex.unlock_nothrow!(core.sync.mutex.Mutex)() nothrow @nogc @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_nothrow
();
} /// A test-and-test-and-set spin lock with backoff. struct
(struct) mutex_throughput.Ttas

A test-and-test-and-set spin lock with backoff.

Ttas
{ shared uint
(field) shared(uint) mutex_throughput.Ttas.state
state
;
void
void mutex_throughput.Ttas.lock() nothrow @nogc @system
lock
() @system nothrow @nogc
{ uint
(local variable) uint round
round
;
while (true) { if (!
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) mutex_throughput.Ttas.state
state
) &&
bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trusted

Performs either compare-and-set or compare-and-swap (or exchange).

There are two categories of overloads in this template: The first category does a simple compare-and-set. The comparison value (ifThis) is treated as an rvalue.

The second category does a compare-and-swap (a.k.a. compare-and-exchange), and expects ifThis to be a pointer type, where the previous value of here will be written.

This operation is both lock-free and atomic.

@paramhere The address of the destination variable.@paramwriteThis The value to store.@paramifThis The comparison value.@returns

true if the store occurred, false if not.

Compare-and-set for shared value type

cas
(&
(field) shared(uint) mutex_throughput.Ttas.state
state
, 0u, 1u))
return; if (++
(local variable) uint round
round
< 64)
foreach (
(local variable) int _
_
; 0 .. 1 << (
(local variable) uint round
round
< 8 ?
(local variable) uint round
round
: 8))
void core.atomic.pause() pure nothrow @nogc @safe

Gives a hint to the processor that the calling thread is in a 'spin-wait' loop, allowing to more efficiently allocate resources.

pause
();
else
int core.sys.posix.sched.sched_yield() nothrow @nogc
sched_yield
();
} } void
void mutex_throughput.Ttas.unlock() nothrow @nogc @system
unlock
() @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) mutex_throughput.Ttas.state
state
, 0u);
} struct
(struct) mutex_throughput.Result
Result
{ double
(field) double mutex_throughput.Result.opsPerUs
opsPerUs
;
double
(field) double mutex_throughput.Result.fairness
fairness
;
double
(field) double mutex_throughput.Result.wakesPerOp
wakesPerOp
,
(field) double mutex_throughput.Result.waitsPerOp
waitsPerOp
;
} /// Runs `threads` threads against one `L` for `ms` milliseconds.
(struct) mutex_throughput.Result
Result
mutex_throughput.Result mutex_throughput.run!(mutex_throughput.Futex3)(uint threads, uint ms) @system

Runs threads threads against one L for ms milliseconds.

run
(L)(uint
(parameter) uint threads
threads
, uint
(parameter) uint ms
ms
) @system
{ static if (is(
(alias) L = mutex_throughput.Futex3
L
== Pthread))
{ 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
;
(struct) mutex_throughput.Pthread

druntime's mutex, a pthread_mutex_t.

Pthread
.
(__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.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
;
} __gshared
(alias) L = mutex_throughput.Futex3
L
(__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).lock
lock
;
__gshared ulong
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).guarded
guarded
; // only touched under the lock
__gshared ulong
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).inside
inside
; // a plain counter: a lost update means a broken lock
static shared ulong
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).sink
sink
;
static shared bool
(shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stop
stop
;
static shared ulong
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakes
wakes
,
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waits
waits
;
void core.atomic.atomicStore!(MemoryOrder.seq, ulong, ulong)(ref shared(ulong) val, ulong 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
(
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakes
wakes
, 0UL);
void core.atomic.atomicStore!(MemoryOrder.seq, ulong, ulong)(ref shared(ulong) val, ulong 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
(
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waits
waits
, 0UL);
(__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).lock
lock
=
(struct) mutex_throughput.Futex3

The three-state futex mutex.

L
.
(constant) mutex_throughput.Futex3 mutex_throughput.Futex3.init = Futex3(0u)
init
;
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).guarded
guarded
= 0;
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).inside
inside
= 0;
void core.atomic.atomicStore!(MemoryOrder.seq, bool, bool)(ref shared(bool) val, bool 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
(
(shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stop
stop
, false);
auto
(local variable) ulong[] counts
counts
= new ulong[
(parameter) uint threads
threads
];
(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
[]
(local variable) core.thread.osthread.Thread[] workers
workers
;
// A factory, not a loop body: closures made in a loop share one frame // (D issue 2043), so every worker would see the last `t`.
(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
core.thread.osthread.Thread mutex_throughput.run!(mutex_throughput.Futex3).worker(uint id) pure nothrow @safe
worker
(uint
(parameter) uint id
id
)
{ return 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
({
ulong
(local variable) ulong n
n
,
(local variable) ulong local
local
=
(parameter) uint id
id
;
while (!
bool core.atomic.atomicLoad!(MemoryOrder.seq, bool)(ref return scope shared(const(bool)) 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
(
(shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stop
stop
))
{
(__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).lock
lock
.
void mutex_throughput.Futex3.lock() nothrow @nogc @system
lock
();
// A short critical section: a few dependent updates. foreach (
(local variable) int _
_
; 0 .. 8)
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).guarded
guarded
=
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).guarded
guarded
* 6_364_136_223_846_793_005UL + 1;
++
(local variable) ulong n
n
;
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).inside
inside
=
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).inside
inside
+ 1;
(__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).lock
lock
.
void mutex_throughput.Futex3.unlock() nothrow @nogc @system
unlock
();
// A little work outside the lock. foreach (
(local variable) int _
_
; 0 .. 16)
(local variable) ulong local
local
=
(local variable) ulong local
local
* 2_862_933_555_777_941_757UL + 3_037_000_493UL;
}
(local variable) ulong[] counts
counts
[
(parameter) uint id
id
] =
(local variable) ulong n
n
;
ulong core.atomic.atomicOp!("+=", ulong, ulong)(ref shared(ulong) val, ulong mod) pure nothrow @nogc @safe

Performs the binary operation 'op' on val using 'mod' as the modifier.

@paramval The target variable.@parammod The modifier to apply.@returnsThe result of the operation.
atomicOp
!"+="(
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).sink
sink
,
(local variable) ulong local
local
); // keep `local` alive
ulong core.atomic.atomicOp!("+=", ulong, ulong)(ref shared(ulong) val, ulong mod) pure nothrow @nogc @safe

Performs the binary operation 'op' on val using 'mod' as the modifier.

@paramval The target variable.@parammod The modifier to apply.@returnsThe result of the operation.
atomicOp
!"+="(
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakes
wakes
,
(thread local global) ulong mutex_throughput.wakeCalls

Wait and wake system calls made by this thread, so the table can show them per acquisition. Thread-local: counting must not add contention.

wakeCalls
);
ulong core.atomic.atomicOp!("+=", ulong, ulong)(ref shared(ulong) val, ulong mod) pure nothrow @nogc @safe

Performs the binary operation 'op' on val using 'mod' as the modifier.

@paramval The target variable.@parammod The modifier to apply.@returnsThe result of the operation.
atomicOp
!"+="(
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waits
waits
,
(thread local global) ulong mutex_throughput.waitCalls

Wait and wake system calls made by this thread, so the table can show them per acquisition. Thread-local: counting must not add contention.

waitCalls
);
}); } foreach (
(local variable) uint t
t
; 0 ..
(parameter) uint threads
threads
)
(local variable) core.thread.osthread.Thread[] workers
workers
~=
core.thread.osthread.Thread mutex_throughput.run!(mutex_throughput.Futex3).worker(uint id) pure nothrow @safe
worker
(
(local variable) uint t
t
);
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 (
(parameter) core.thread.osthread.Thread w
w
;
(local variable) core.thread.osthread.Thread[] workers
workers
)
(local variable) core.thread.osthread.Thread w
w
.
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
();
(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
.
void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trusted

Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.

In

period must be non-negative.

Example


Thread.sleep( dur!("msecs")( 50 ) );  // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds

@paramval The minimum duration the calling thread should be suspended.
sleep
(
(parameter) uint ms
ms
.msecs);
void core.atomic.atomicStore!(MemoryOrder.seq, bool, bool)(ref shared(bool) val, bool 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
(
(shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stop
stop
, true);
foreach (
(parameter) core.thread.osthread.Thread w
w
;
(local variable) core.thread.osthread.Thread[] workers
workers
)
(local variable) core.thread.osthread.Thread w
w
.
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
();
const
(local variable) const(long) us
us
= (
(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
).
long core.time.Duration.total!"usecs"() 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
!"usecs";
assert(
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).inside
inside
==
(local variable) ulong[] counts
counts
.
ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safe

Sums elements of r, which must be a finite input range. Although conceptually sum`(`r`)` is equivalent to `fold`!((a, b) => a + b)(`r`, 0), sum`` uses specialized algorithms to maximize accuracy, as follows.

  • If ElementType!R is a floating-point type and R is a random-access range with length and slicing, then sum uses the pairwise summation algorithm.

  • If ElementType!R is a floating-point type and R is a finite input range (but not a random-access range with slicing), then sum uses the Kahan summation algorithm.

  • In all other cases, a simple element by element addition is done.

For floating point inputs, calculations are made in spec/type, Types, real precision for real inputs and in double precision otherwise (Note this is a special case that deviates from fold's behavior, which would have kept float precision for a float range). For all other types, the calculations are done in the same type obtained from from adding two elements of the range, which may be a different type from the elements themselves (for example, in case of integral promotion).

A seed may be passed to sum. Not only will this seed be used as an initial value, but its type will override all the above, and determine the algorithm and precision used for summation. If a seed is not passed, one is created with the value of typeof(r.front + r.front)(0), or typeof(r.front + r.front).zero if no constructor exists that takes an int.

Note that these specialized summing algorithms execute more primitive operations than vanilla summation. Therefore, if in certain cases maximum speed is required at expense of precision, one can use fold!((a, b) => a + b)(r, 0), which is not specialized for summation.

@paramseed the initial value of the summation@paramr a finite input range@returnsThe sum of all the elements in the range r.
sum
,
(struct) mutex_throughput.Futex3

The three-state futex mutex.

L
.
(constant) string mutex_throughput.Futex3.stringof = "Futex3"
stringof
~ " let two threads into the critical section");
return
(struct) mutex_throughput.Result
Result
(
(local variable) ulong[] counts
counts
.
ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safe

Sums elements of r, which must be a finite input range. Although conceptually sum`(`r`)` is equivalent to `fold`!((a, b) => a + b)(`r`, 0), sum`` uses specialized algorithms to maximize accuracy, as follows.

  • If ElementType!R is a floating-point type and R is a random-access range with length and slicing, then sum uses the pairwise summation algorithm.

  • If ElementType!R is a floating-point type and R is a finite input range (but not a random-access range with slicing), then sum uses the Kahan summation algorithm.

  • In all other cases, a simple element by element addition is done.

For floating point inputs, calculations are made in spec/type, Types, real precision for real inputs and in double precision otherwise (Note this is a special case that deviates from fold's behavior, which would have kept float precision for a float range). For all other types, the calculations are done in the same type obtained from from adding two elements of the range, which may be a different type from the elements themselves (for example, in case of integral promotion).

A seed may be passed to sum. Not only will this seed be used as an initial value, but its type will override all the above, and determine the algorithm and precision used for summation. If a seed is not passed, one is created with the value of typeof(r.front + r.front)(0), or typeof(r.front + r.front).zero if no constructor exists that takes an int.

Note that these specialized summing algorithms execute more primitive operations than vanilla summation. Therefore, if in certain cases maximum speed is required at expense of precision, one can use fold!((a, b) => a + b)(r, 0), which is not specialized for summation.

@paramseed the initial value of the summation@paramr a finite input range@returnsThe sum of all the elements in the range r.
sum
/ cast(double)
(local variable) const(long) us
us
,
(local variable) ulong[] counts
counts
.
ulong std.algorithm.searching.minElement!((a) => a, ulong[])(ulong[] r) pure nothrow @nogc @safe

Iterates the passed range and returns the minimal element. A custom mapping function can be passed to map. In other languages this is sometimes called argmin.

Complexity

O(n) Exactly n - 1 comparisons are needed.

Precondition

If a seed is not given, r must not be empty.

Note

If at least one of the arguments is NaN, the result is an unspecified value.

If you want to ignore NaNs, you can use filter and isNaN to remove them, before applying minElement. Add a suitable seed, to avoid error messages if all elements are NaNs:

<range>.filter!(a=>!a.isNaN).minElement(<seed>);

If you want to get NaN as a result if a NaN is present in the range, you can use fold and isNaN:

<range>.fold!((a,b)=>a.isNaN || b.isNaN ? real.nan : a < b ? a : b);
@parammap custom accessor for the comparison key@paramr range from which the minimal element will be selected@paramseed custom seed to use as initial element@returnsThe minimal element of the passed-in range.@seeextrema, maxElement, min, minCount, minIndex, minPos
minElement
/ cast(double)
(local variable) ulong[] counts
counts
.
ulong std.algorithm.searching.maxElement!((a) => a, ulong[])(ulong[] r) pure nothrow @nogc @safe

Iterates the passed range and returns the maximal element. A custom mapping function can be passed to map. In other languages this is sometimes called argmax.

Complexity

O(n) Exactly n - 1 comparisons are needed.

Precondition

If a seed is not given, r must not be empty.

Note

If at least one of the arguments is NaN, the result is an unspecified value. See minElement for examples on how to cope with NaNs.

@parammap custom accessor for the comparison key@paramr range from which the maximum element will be selected@paramseed custom seed to use as initial element@returnsThe maximal element of the passed-in range.@seeextrema, minElement, max, maxCount, maxIndex, maxPos
maxElement
,
ulong core.atomic.atomicLoad!(MemoryOrder.seq, ulong)(ref return scope shared(const(ulong)) 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
(
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakes
wakes
) / cast(double)
(local variable) ulong[] counts
counts
.
ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safe

Sums elements of r, which must be a finite input range. Although conceptually sum`(`r`)` is equivalent to `fold`!((a, b) => a + b)(`r`, 0), sum`` uses specialized algorithms to maximize accuracy, as follows.

  • If ElementType!R is a floating-point type and R is a random-access range with length and slicing, then sum uses the pairwise summation algorithm.

  • If ElementType!R is a floating-point type and R is a finite input range (but not a random-access range with slicing), then sum uses the Kahan summation algorithm.

  • In all other cases, a simple element by element addition is done.

For floating point inputs, calculations are made in spec/type, Types, real precision for real inputs and in double precision otherwise (Note this is a special case that deviates from fold's behavior, which would have kept float precision for a float range). For all other types, the calculations are done in the same type obtained from from adding two elements of the range, which may be a different type from the elements themselves (for example, in case of integral promotion).

A seed may be passed to sum. Not only will this seed be used as an initial value, but its type will override all the above, and determine the algorithm and precision used for summation. If a seed is not passed, one is created with the value of typeof(r.front + r.front)(0), or typeof(r.front + r.front).zero if no constructor exists that takes an int.

Note that these specialized summing algorithms execute more primitive operations than vanilla summation. Therefore, if in certain cases maximum speed is required at expense of precision, one can use fold!((a, b) => a + b)(r, 0), which is not specialized for summation.

@paramseed the initial value of the summation@paramr a finite input range@returnsThe sum of all the elements in the range r.
sum
,
ulong core.atomic.atomicLoad!(MemoryOrder.seq, ulong)(ref return scope shared(const(ulong)) 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
(
(shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waits
waits
) / cast(double)
(local variable) ulong[] counts
counts
.
ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safe

Sums elements of r, which must be a finite input range. Although conceptually sum`(`r`)` is equivalent to `fold`!((a, b) => a + b)(`r`, 0), sum`` uses specialized algorithms to maximize accuracy, as follows.

  • If ElementType!R is a floating-point type and R is a random-access range with length and slicing, then sum uses the pairwise summation algorithm.

  • If ElementType!R is a floating-point type and R is a finite input range (but not a random-access range with slicing), then sum uses the Kahan summation algorithm.

  • In all other cases, a simple element by element addition is done.

For floating point inputs, calculations are made in spec/type, Types, real precision for real inputs and in double precision otherwise (Note this is a special case that deviates from fold's behavior, which would have kept float precision for a float range). For all other types, the calculations are done in the same type obtained from from adding two elements of the range, which may be a different type from the elements themselves (for example, in case of integral promotion).

A seed may be passed to sum. Not only will this seed be used as an initial value, but its type will override all the above, and determine the algorithm and precision used for summation. If a seed is not passed, one is created with the value of typeof(r.front + r.front)(0), or typeof(r.front + r.front).zero if no constructor exists that takes an int.

Note that these specialized summing algorithms execute more primitive operations than vanilla summation. Therefore, if in certain cases maximum speed is required at expense of precision, one can use fold!((a, b) => a + b)(r, 0), which is not specialized for summation.

@paramseed the initial value of the summation@paramr a finite input range@returnsThe sum of all the elements in the range r.
sum
);
} void
void D main() @system
main
() @system
{ const
(local variable) immutable(uint) cores
cores
= totalCPUs;
uint[]
(local variable) uint[] threadCounts
threadCounts
= [1, 2, 4];
if (
(local variable) immutable(uint) cores
cores
> 4)
(local variable) uint[] threadCounts
threadCounts
~=
(local variable) immutable(uint) cores
cores
;
(local variable) uint[] threadCounts
threadCounts
~= 2 *
(local variable) immutable(uint) cores
cores
; // oversubscribed
enum uint
(constant) uint mutex_throughput.main.ms = 100u
ms
= 100;
void std.stdio.writefln!(char, immutable(uint), uint)(in char[] fmt, immutable(uint) __param_1, uint __param_2) @safe

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

writefln
("%u hardware threads; %u ms per cell; ops/µs, fairness (min/max ops per thread); per op: waits, wakes",
(local variable) immutable(uint) cores
cores
,
(constant) uint mutex_throughput.main.ms = 100u
ms
);
void std.stdio.writefln!(char, string, string)(in char[] fmt, string __param_1, string __param_2) @safe

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

writefln
("%-9s%s", "threads",
string std.format.format!("%-28s%-28s%-28s%-20s%-20s", string, string, string, string, string)(string __param_0, string __param_1, string __param_2, string __param_3, string __param_4) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%-28s%-28s%-28s%-20s%-20s"("futex3", "parking", "parking+desig", "pthread", "ttas"));
foreach (
(parameter) uint n
n
;
(local variable) uint[] threadCounts
threadCounts
)
{
(alias) object.string = string
string
(local variable) string row
row
;
static foreach (L; [`Futex3`, `Parking`, `ParkingDesig`, `Pthread`, `Ttas`]) {{ const
(local variable) const(mutex_throughput.Result) r
r
=
mutex_throughput.Result mutex_throughput.run!(mutex_throughput.Futex3)(uint threads, uint ms) @system

Runs threads threads against one L for ms milliseconds.

run
!(mixin(L))(
(local variable) uint n
n
,
(constant) uint mutex_throughput.main.ms = 100u
ms
);
(local variable) string row
row
~= (
(constant) string mutex_throughput.main.L = "Futex3"
L
== `Pthread` ||
(constant) string mutex_throughput.main.L = "Futex3"
L
== `Ttas`
?
string std.format.format!("%-20s", string)(string __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%-20s"(
string std.format.format!("%7.2f %.2f", const(double), const(double))(const(double) __param_0, const(double) __param_1) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%7.2f %.2f"(
(local variable) const(mutex_throughput.Result) r
r
.
(field) double mutex_throughput.Result.opsPerUs
opsPerUs
,
(local variable) const(mutex_throughput.Result) r
r
.
(field) double mutex_throughput.Result.fairness
fairness
))
:
string std.format.format!("%-28s", string)(string __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%-28s"(
string std.format.format!("%7.2f %.2f %.3f %.3f", const(double), const(double), const(double), const(double))(const(double) __param_0, const(double) __param_1, const(double) __param_2, const(double) __param_3) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%7.2f %.2f %.3f %.3f"(
(local variable) const(mutex_throughput.Result) r
r
.
(field) double mutex_throughput.Result.opsPerUs
opsPerUs
,
(local variable) const(mutex_throughput.Result) r
r
.
(field) double mutex_throughput.Result.fairness
fairness
,
(local variable) const(mutex_throughput.Result) r
r
.
(field) double mutex_throughput.Result.waitsPerOp
waitsPerOp
,
(local variable) const(mutex_throughput.Result) r
r
.
(field) double mutex_throughput.Result.wakesPerOp
wakesPerOp
)));
}}
void std.stdio.writefln!(char, string, string)(in char[] fmt, string __param_1, string __param_2) @safe

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

writefln
("%-9s%s",
(local variable) uint n
n
== 2 *
(local variable) immutable(uint) cores
cores
?
string std.format.format!("%u*", uint)(uint __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%u*"(
(local variable) uint n
n
) :
string std.format.format!("%u", uint)(uint __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%u"(
(local variable) uint n
n
),
(local variable) string row
row
);
}
void std.stdio.writeln!string(string __param_0) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("* oversubscribed: more threads than hardware threads");
}