#!/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_throughputThroughput 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 (linuxlinux)
version = (version) futexBenchfutexBench;
version (futexBenchfutexBench) {} else
{
void main()
{
import std.stdio : writeln;
writeln("SKIP: the futex-based locks need Linux");
}
}
version (futexBenchfutexBench):
import (package) corecore.(module) core.atomicThe atomic module provides basic support for lock-free
concurrent programming.
Use the -preview=nosharedaccess compiler flag to detect
unsafe individual read or write operations on shared data.
Source
core/atomic.d
Examples
int y = 2;
shared int x = y; // OK
//x++; // read modify write error
x.atomicOp!"+="(1); // OK
//y = x; // read error with preview flag
y = x.atomicLoad(); // OK
assert(y == 3);
//x = 5; // write error with preview flag
x.atomicStore(5); // OK
assert(x.atomicLoad() == 5);
atomic : (alias template) 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.
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.
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.
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.
cas, (alias) mutex_throughput.pause = void core.atomic.pause() pure nothrow @nogc @safeGives a hint to the processor that the calling thread is in a 'spin-wait' loop,
allowing to more efficiently allocate resources.
pause;
import (package) corecore.(package) core.syssys.(package) core.sys.linuxlinux.(module) core.sys.linux.unistdunistd : (alias) mutex_throughput.syscall = long core.sys.linux.unistd.syscall(long sysno, ...) nothrow @nogcInvoke system call number sysno, passing it the remaining arguments.
syscall;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.schedD header file for POSIX.
sched : (alias) mutex_throughput.sched_yield = int core.sys.posix.sched.sched_yield() nothrow @nogcsched_yield;
import (package) corecore.(module) core.threadThe thread module provides support for thread creation and management.
Source
core/thread/package.d
thread : (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread;
import (package) corecore.(module) core.timeModule containing core time functionality, such as Duration (which
represents a duration of time) or MonoTime (which represents a
timestamp of the system's monotonic clock).
Various functions take a string (or strings) to represent a unit of time
(e.g. convert!("days", "hours")(numDays)). The valid strings to use
with such functions are "years", "months", "weeks", "days", "hours",
"minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds),
"hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There
are a few functions that also allow "nsecs", but very little actually
has precision greater than hnsecs.
Symbol Description Types Duration Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). TickDuration DEPRECATED Represents a duration of time in system clock ticks, using the highest precision that the system provides. MonoTime Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides. Functions convert Generic way of converting between two time units. dur Allows constructing a Duration from the given time units with the given length. weeks days hours
minutes seconds msecs
usecs hnsecs nsecs |
Convenience aliases for dur. |
| abs | Returns the absolute value of a duration. |
From Duration
From TickDuration
From units
To Duration tickDuration.to, std,conv!Duration() dur!"msecs"(5) or 5.msecs()
| To TickDuration |
duration.to, std,conv!TickDuration() |
|
TickDuration.from!"msecs"(msecs) |
| To units |
duration.total!"days" |
tickDuration.msecs |
convert!("days", "msecs")(msecs) |
Source
core/time.d
time : (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime, msecs;
import (package) stdstd.(module) std.algorithmThis 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
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.
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);
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.
sum;
import (package) stdstd.(module) std.formatThis 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*:
**'-'**|**'+'**|**' '**|**'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. |
| '+' / *' '* |
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");
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.
format;
import (package) stdstd.(module) std.parallelismstd.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
parallelism : totalCPUs;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) 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);
}
}
writeln;
version (X86_64X86_64)
enum long (constant) long mutex_throughput.sysFutex = 202LsysFutex = 202;
else version (AArch64)
enum long sysFutex = 98;
else
static assert(0, "add this architecture's futex system call number");
enum int (constant) int mutex_throughput.futexWaitPrivate = 128futexWaitPrivate = 128, (constant) int mutex_throughput.futexWakePrivate = 129futexWakePrivate = 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.wakeCallsWait 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.waitCallsWait 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 @systemfutexWait(shared(uint)* (parameter) shared(uint)* wordword, uint (parameter) uint expectedexpected) @system nothrow @nogc
{
++(thread local global) ulong mutex_throughput.waitCallsWait 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 @nogcInvoke system call number sysno, passing it the remaining arguments.
syscall((constant) long mutex_throughput.sysFutex = 202LsysFutex, (parameter) shared(uint)* wordword, (constant) int mutex_throughput.futexWaitPrivate = 128futexWaitPrivate, (parameter) uint expectedexpected, null, null, 0);
}
void void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @systemfutexWake(shared(uint)* (parameter) shared(uint)* wordword, int (parameter) int countcount) @system nothrow @nogc
{
++(thread local global) ulong mutex_throughput.wakeCallsWait 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 @nogcInvoke system call number sysno, passing it the remaining arguments.
syscall((constant) long mutex_throughput.sysFutex = 202LsysFutex, (parameter) shared(uint)* wordword, (constant) int mutex_throughput.futexWakePrivate = 129futexWakePrivate, (parameter) int countcount, null, null, 0);
}
/// The three-state futex mutex.
struct (struct) mutex_throughput.Futex3The three-state futex mutex.
Futex3
{
enum uint (constant) uint mutex_throughput.Futex3.unlocked = 0uunlocked = 0, (constant) uint mutex_throughput.Futex3.locked = 1ulocked = 1, (constant) uint mutex_throughput.Futex3.contended = 2ucontended = 2;
shared uint (field) shared(uint) mutex_throughput.Futex3.statestate;
void void mutex_throughput.Futex3.lock() nothrow @nogc @systemlock() @system nothrow @nogc
{
if (bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Futex3.statestate, (constant) uint mutex_throughput.Futex3.unlocked = 0uunlocked, (constant) uint mutex_throughput.Futex3.locked = 1ulocked))
return;
// Spin while the lock is held but nobody waits (Rust std: 100).
foreach ((local variable) int __; 0 .. 100)
{
const (local variable) const(uint) ss = uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.Futex3.statestate);
if ((local variable) const(uint) ss == (constant) uint mutex_throughput.Futex3.unlocked = 0uunlocked && bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Futex3.statestate, (constant) uint mutex_throughput.Futex3.unlocked = 0uunlocked, (constant) uint mutex_throughput.Futex3.locked = 1ulocked))
return;
if ((local variable) const(uint) ss == (constant) uint mutex_throughput.Futex3.contended = 2ucontended)
break;
void core.atomic.pause() pure nothrow @nogc @safeGives 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 @systematomicExchange(&(field) shared(uint) mutex_throughput.Futex3.statestate, (constant) uint mutex_throughput.Futex3.contended = 2ucontended) != (constant) uint mutex_throughput.Futex3.unlocked = 0uunlocked)
void mutex_throughput.futexWait(shared(uint)* word, uint expected) nothrow @nogc @systemfutexWait(&(field) shared(uint) mutex_throughput.Futex3.statestate, (constant) uint mutex_throughput.Futex3.contended = 2ucontended);
}
void void mutex_throughput.Futex3.unlock() nothrow @nogc @systemunlock() @system nothrow @nogc
{
if (uint mutex_throughput.atomicExchange(shared(uint)* p, uint v) nothrow @nogc @systematomicExchange(&(field) shared(uint) mutex_throughput.Futex3.statestate, (constant) uint mutex_throughput.Futex3.unlocked = 0uunlocked) == (constant) uint mutex_throughput.Futex3.contended = 2ucontended)
void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @systemfutexWake(&(field) shared(uint) mutex_throughput.Futex3.statestate, 1);
}
}
uint uint mutex_throughput.atomicExchange(shared(uint)* p, uint v) nothrow @nogc @systematomicExchange(shared(uint)* (parameter) shared(uint)* pp, uint (parameter) uint vv) @system nothrow @nogc
{
import (package) corecore.(module) core.atomicThe atomic module provides basic support for lock-free
concurrent programming.
Use the -preview=nosharedaccess compiler flag to detect
unsafe individual read or write operations on shared data.
Source
core/atomic.d
Examples
int y = 2;
shared int x = y; // OK
//x++; // read modify write error
x.atomicOp!"+="(1); // OK
//y = x; // read error with preview flag
y = x.atomicLoad(); // OK
assert(y == 3);
//x = 5; // write error with preview flag
x.atomicStore(5); // OK
assert(x.atomicLoad() == 5);
atomic : (alias template) 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 @trustedExchange exchangeWith with the memory referenced by here.
This operation is both lock-free and atomic.
atomicExchange((parameter) shared(uint)* pp, (parameter) uint vv);
}
/// One parked thread's record, in the waiting thread's own storage.
struct (struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter
{
const(void)* (field) const(void)* mutex_throughput.Waiter.keykey;
(struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter* (field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext;
shared uint (field) shared(uint) mutex_throughput.Waiter.unparkedunparked;
}
/// A bucket of the global wait-queue table: a spin lock and a FIFO.
struct (struct) mutex_throughput.BucketA bucket of the global wait-queue table: a spin lock and a FIFO.
Bucket
{
shared uint (field) shared(uint) mutex_throughput.Bucket.guardguard;
(struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter* (field) mutex_throughput.Waiter* mutex_throughput.Bucket.headhead, (field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail;
ubyte[64 - uint.(constant) ulong uint.sizeof = 4LUsizeof - 2 * ((struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter*).(constant) ulong mutex_throughput.Waiter*.sizeof = 8LUsizeof] (field) ubyte[44] mutex_throughput.Bucket.padpad;
void void mutex_throughput.Bucket.acquire() nothrow @nogc @systemacquire() @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 @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.Bucket.guardguard) || !bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Bucket.guardguard, 0u, 1u))
void core.atomic.pause() pure nothrow @nogc @safeGives 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 @systemrelease() @system nothrow @nogc => void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((field) shared(uint) mutex_throughput.Bucket.guardguard, 0u);
}
__gshared (struct) mutex_throughput.BucketA bucket of the global wait-queue table: a spin lock and a FIFO.
Bucket[256] (__gshared global) mutex_throughput.Bucket[256] mutex_throughput.tabletable;
ref (struct) mutex_throughput.BucketA 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 @systembucketOf(const(void)* (parameter) const(void)* keykey) @system nothrow @nogc
{
// Fibonacci hashing of the address.
const (local variable) const(ulong) hh = (cast((alias) object.size_t = ulongsize_t) (parameter) const(void)* keykey * 0x9E3779B97F4A7C15UL) >> ((ulong) ulongsize_t.(constant) ulong ulong.sizeof = 8LUsizeof * 8 - 8);
return (__gshared global) mutex_throughput.Bucket[256] mutex_throughput.tabletable[(local variable) const(ulong) hh];
}
/// The one-byte parking-lot mutex (held in a `uint` only for `cas`).
struct (struct) mutex_throughput.ParkingThe one-byte parking-lot mutex (held in a uint only for cas).
Parking
{
enum uint (constant) uint mutex_throughput.Parking.lockedBit = 1ulockedBit = 1, (constant) uint mutex_throughput.Parking.parkedBit = 2uparkedBit = 2;
shared uint (field) shared(uint) mutex_throughput.Parking.statestate;
void void mutex_throughput.Parking.lock() nothrow @nogc @systemlock() @system nothrow @nogc
{
if (bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Parking.statestate, 0u, (constant) uint mutex_throughput.Parking.lockedBit = 1ulockedBit))
return;
void mutex_throughput.Parking.lockSlow() nothrow @nogc @systemlockSlow();
}
void void mutex_throughput.Parking.lockSlow() nothrow @nogc @systemlockSlow() @system nothrow @nogc
{
uint (local variable) uint spinsspins;
while (true)
{
auto (local variable) uint ss = uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.Parking.statestate);
if (!((local variable) uint ss & (constant) uint mutex_throughput.Parking.lockedBit = 1ulockedBit))
{
if (bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Parking.statestate, (local variable) uint ss, (local variable) uint ss | (constant) uint mutex_throughput.Parking.lockedBit = 1ulockedBit))
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 ss & (constant) uint mutex_throughput.Parking.parkedBit = 2uparkedBit) && (local variable) uint spinsspins < 10)
{
++(local variable) uint spinsspins;
if ((local variable) uint spinsspins <= 3)
foreach ((local variable) int __; 0 .. 1 << (local variable) uint spinsspins)
void core.atomic.pause() pure nothrow @nogc @safeGives 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 @nogcsched_yield();
continue;
}
if (!((local variable) uint ss & (constant) uint mutex_throughput.Parking.parkedBit = 2uparkedBit) && !bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Parking.statestate, (local variable) uint ss, (local variable) uint ss | (constant) uint mutex_throughput.Parking.parkedBit = 2uparkedBit))
continue;
// Park: validate under the bucket lock, enqueue, sleep.
(struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter (local variable) mutex_throughput.Waiter meme;
(local variable) mutex_throughput.Waiter meme.(field) const(void)* mutex_throughput.Waiter.keykey = &this;
auto (local variable) mutex_throughput.Bucket* bb = &mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @systembucketOf(&this);
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.acquire() nothrow @nogc @systemacquire();
if (uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.Parking.statestate) != ((constant) uint mutex_throughput.Parking.lockedBit = 1ulockedBit | (constant) uint mutex_throughput.Parking.parkedBit = 2uparkedBit))
{
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.release() nothrow @nogc @systemrelease();
continue;
}
if ((local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail)
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext = &(local variable) mutex_throughput.Waiter meme;
else
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.headhead = &(local variable) mutex_throughput.Waiter meme;
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail = &(local variable) mutex_throughput.Waiter meme;
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.release() nothrow @nogc @systemrelease();
while (!uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((local variable) mutex_throughput.Waiter meme.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked))
void mutex_throughput.futexWait(shared(uint)* word, uint expected) nothrow @nogc @systemfutexWait(&(local variable) mutex_throughput.Waiter meme.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked, 0);
(local variable) uint spinsspins = 0;
}
}
void void mutex_throughput.Parking.unlock() nothrow @nogc @systemunlock() @system nothrow @nogc
{
if (bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Parking.statestate, (constant) uint mutex_throughput.Parking.lockedBit = 1ulockedBit, 0u))
return;
// Someone is parked: dequeue the first waiter for this lock.
auto (local variable) mutex_throughput.Bucket* bb = &mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @systembucketOf(&this);
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.acquire() nothrow @nogc @systemacquire();
(struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter* (local variable) mutex_throughput.Waiter* prevprev, (local variable) mutex_throughput.Waiter* ww = (local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.headhead;
while ((local variable) mutex_throughput.Waiter* ww && (local variable) mutex_throughput.Waiter* ww.(field) const(void)* mutex_throughput.Waiter.keykey !is &this)
{
(local variable) mutex_throughput.Waiter* prevprev = (local variable) mutex_throughput.Waiter* ww;
(local variable) mutex_throughput.Waiter* ww = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext;
}
bool (local variable) bool moremore;
if ((local variable) mutex_throughput.Waiter* ww)
{
if ((local variable) mutex_throughput.Waiter* prevprev)
(local variable) mutex_throughput.Waiter* prevprev.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext;
else
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.headhead = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext;
if ((local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail is (local variable) mutex_throughput.Waiter* ww)
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail = (local variable) mutex_throughput.Waiter* prevprev;
for (auto (local variable) mutex_throughput.Waiter* oo = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext; o; o = o.next)
if ((local variable) mutex_throughput.Waiter* oo.(field) const(void)* mutex_throughput.Waiter.keykey is &this)
{
(local variable) bool moremore = 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 @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((field) shared(uint) mutex_throughput.Parking.statestate, (local variable) bool moremore ? (constant) uint mutex_throughput.Parking.parkedBit = 2uparkedBit : 0u);
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.release() nothrow @nogc @systemrelease();
if ((local variable) mutex_throughput.Waiter* ww)
{
void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((local variable) mutex_throughput.Waiter* ww.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked, 1u);
void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @systemfutexWake(&(local variable) mutex_throughput.Waiter* ww.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked, 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.ParkingDesigThe 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 = 1ulockedBit = 1, (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit = 2, (constant) uint mutex_throughput.ParkingDesig.wokenBit = 4uwokenBit = 4;
shared uint (field) shared(uint) mutex_throughput.ParkingDesig.statestate;
void void mutex_throughput.ParkingDesig.lock() nothrow @nogc @systemlock() @system nothrow @nogc
{
if (bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.ParkingDesig.statestate, 0u, (constant) uint mutex_throughput.ParkingDesig.lockedBit = 1ulockedBit))
return;
void mutex_throughput.ParkingDesig.lockSlow() nothrow @nogc @systemlockSlow();
}
void void mutex_throughput.ParkingDesig.lockSlow() nothrow @nogc @systemlockSlow() @system nothrow @nogc
{
uint (local variable) uint spinsspins;
bool (local variable) bool designateddesignated;
while (true)
{
auto (local variable) uint ss = uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.ParkingDesig.statestate);
if (!((local variable) uint ss & (constant) uint mutex_throughput.ParkingDesig.lockedBit = 1ulockedBit))
{
const (local variable) const(uint) nextnext = ((local variable) uint ss | (constant) uint mutex_throughput.ParkingDesig.lockedBit = 1ulockedBit) & ((local variable) bool designateddesignated ? ~(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4uwokenBit : ~0u);
if (bool core.atomic.cas!().cas!(uint, uint, const(uint))(shared(uint)* here, uint ifThis, const(uint) writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.ParkingDesig.statestate, (local variable) uint ss, (local variable) const(uint) nextnext))
return;
continue;
}
if (!((local variable) uint ss & (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit) && (local variable) uint spinsspins < 10)
{
++(local variable) uint spinsspins;
if ((local variable) uint spinsspins <= 3)
foreach ((local variable) int __; 0 .. 1 << (local variable) uint spinsspins)
void core.atomic.pause() pure nothrow @nogc @safeGives 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 @nogcsched_yield();
continue;
}
// About to sleep again: give up the designation first.
if ((local variable) bool designateddesignated)
{
if (!bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.ParkingDesig.statestate, (local variable) uint ss, (local variable) uint ss & ~(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4uwokenBit))
continue;
(local variable) bool designateddesignated = false;
(local variable) uint ss &= ~(constant) uint mutex_throughput.ParkingDesig.wokenBit = 4uwokenBit;
}
if (!((local variable) uint ss & (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit) && !bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.ParkingDesig.statestate, (local variable) uint ss, (local variable) uint ss | (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit))
continue;
(struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter (local variable) mutex_throughput.Waiter meme;
(local variable) mutex_throughput.Waiter meme.(field) const(void)* mutex_throughput.Waiter.keykey = &this;
auto (local variable) mutex_throughput.Bucket* bb = &mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @systembucketOf(&this);
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.acquire() nothrow @nogc @systemacquire();
const (local variable) const(uint) vv = uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.ParkingDesig.statestate);
if (((local variable) const(uint) vv & ((constant) uint mutex_throughput.ParkingDesig.lockedBit = 1ulockedBit | (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit)) != ((constant) uint mutex_throughput.ParkingDesig.lockedBit = 1ulockedBit | (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit))
{
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.release() nothrow @nogc @systemrelease();
continue;
}
if ((local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail)
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext = &(local variable) mutex_throughput.Waiter meme;
else
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.headhead = &(local variable) mutex_throughput.Waiter meme;
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail = &(local variable) mutex_throughput.Waiter meme;
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.release() nothrow @nogc @systemrelease();
while (!uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((local variable) mutex_throughput.Waiter meme.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked))
void mutex_throughput.futexWait(shared(uint)* word, uint expected) nothrow @nogc @systemfutexWait(&(local variable) mutex_throughput.Waiter meme.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked, 0);
(local variable) bool designateddesignated = true;
(local variable) uint spinsspins = 0;
}
}
void void mutex_throughput.ParkingDesig.unlock() nothrow @nogc @systemunlock() @system nothrow @nogc
{
if (bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.ParkingDesig.statestate, (constant) uint mutex_throughput.ParkingDesig.lockedBit = 1ulockedBit, 0u))
return;
while (true)
{
const (local variable) const(uint) ss = uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.ParkingDesig.statestate);
// A designated waker is already on its way: just release.
if (((local variable) const(uint) ss & (constant) uint mutex_throughput.ParkingDesig.wokenBit = 4uwokenBit) || !((local variable) const(uint) ss & (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit))
{
if (bool core.atomic.cas!().cas!(uint, const(uint), uint)(shared(uint)* here, const(uint) ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.ParkingDesig.statestate, (local variable) const(uint) ss, (local variable) const(uint) ss & ~(constant) uint mutex_throughput.ParkingDesig.lockedBit = 1ulockedBit))
return;
continue;
}
break;
}
auto (local variable) mutex_throughput.Bucket* bb = &mutex_throughput.Bucket mutex_throughput.bucketOf(const(void)* key) nothrow @nogc ref @systembucketOf(&this);
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.acquire() nothrow @nogc @systemacquire();
(struct) mutex_throughput.WaiterOne parked thread's record, in the waiting thread's own storage.
Waiter* (local variable) mutex_throughput.Waiter* prevprev, (local variable) mutex_throughput.Waiter* ww = (local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.headhead;
while ((local variable) mutex_throughput.Waiter* ww && (local variable) mutex_throughput.Waiter* ww.(field) const(void)* mutex_throughput.Waiter.keykey !is &this)
{
(local variable) mutex_throughput.Waiter* prevprev = (local variable) mutex_throughput.Waiter* ww;
(local variable) mutex_throughput.Waiter* ww = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext;
}
bool (local variable) bool moremore;
if ((local variable) mutex_throughput.Waiter* ww)
{
if ((local variable) mutex_throughput.Waiter* prevprev)
(local variable) mutex_throughput.Waiter* prevprev.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext;
else
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.headhead = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext;
if ((local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail is (local variable) mutex_throughput.Waiter* ww)
(local variable) mutex_throughput.Bucket* bb.(field) mutex_throughput.Waiter* mutex_throughput.Bucket.tailtail = (local variable) mutex_throughput.Waiter* prevprev;
for (auto (local variable) mutex_throughput.Waiter* oo = (local variable) mutex_throughput.Waiter* ww.(field) mutex_throughput.Waiter* mutex_throughput.Waiter.nextnext; o; o = o.next)
if ((local variable) mutex_throughput.Waiter* oo.(field) const(void)* mutex_throughput.Waiter.keykey is &this)
{
(local variable) bool moremore = true;
break;
}
}
void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((field) shared(uint) mutex_throughput.ParkingDesig.statestate, ((local variable) bool moremore ? (constant) uint mutex_throughput.ParkingDesig.parkedBit = 2uparkedBit : 0u) | ((local variable) mutex_throughput.Waiter* ww ? (constant) uint mutex_throughput.ParkingDesig.wokenBit = 4uwokenBit : 0u));
(local variable) mutex_throughput.Bucket* bb.void mutex_throughput.Bucket.release() nothrow @nogc @systemrelease();
if ((local variable) mutex_throughput.Waiter* ww)
{
void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((local variable) mutex_throughput.Waiter* ww.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked, 1u);
void mutex_throughput.futexWake(shared(uint)* word, int count) nothrow @nogc @systemfutexWake(&(local variable) mutex_throughput.Waiter* ww.(field) shared(uint) mutex_throughput.Waiter.unparkedunparked, 1);
}
}
}
/// druntime's mutex, a `pthread_mutex_t`.
struct (struct) mutex_throughput.Pthreaddruntime's mutex, a pthread_mutex_t.
Pthread
{
import (package) corecore.(package) core.syncsync.(module) core.sync.mutexThe mutex module provides a primitive for maintaining mutually exclusive
access.
Source
core/sync/mutex.d
mutex : (class) core.sync.mutex.MutexThis class represents a general purpose, recursive mutex.
Implemented using pthread_mutex on Posix and CRITICAL_SECTION
on Windows.
Examples
import core.thread : Thread;
class Resource
{
Mutex mtx;
int cargo;
this() shared @safe nothrow
{
mtx = new shared Mutex();
cargo = 42;
}
void useResource() shared @trusted nothrow @nogc
{
mtx.lock_nothrow();
(cast() cargo) += 1;
mtx.unlock_nothrow();
}
}
shared Resource res = new shared Resource();
auto otherThread = new Thread(
{
foreach (i; 0 .. 10000)
res.useResource();
}).start();
foreach (i; 0 .. 10000)
res.useResource();
otherThread.join();
assert (res.cargo == 20042);
Mutex;
__gshared (class) core.sync.mutex.MutexThis class represents a general purpose, recursive mutex.
Implemented using pthread_mutex on Posix and CRITICAL_SECTION
on Windows.
Examples
import core.thread : Thread;
class Resource
{
Mutex mtx;
int cargo;
this() shared @safe nothrow
{
mtx = new shared Mutex();
cargo = 42;
}
void useResource() shared @trusted nothrow @nogc
{
mtx.lock_nothrow();
(cast() cargo) += 1;
mtx.unlock_nothrow();
}
}
shared Resource res = new shared Resource();
auto otherThread = new Thread(
{
foreach (i; 0 .. 10000)
res.useResource();
}).start();
foreach (i; 0 .. 10000)
res.useResource();
otherThread.join();
assert (res.cargo == 20042);
Mutex (__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.mm;
void void mutex_throughput.Pthread.lock() nothrow @nogc @systemlock() @system nothrow @nogc => (__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.mm.void core.sync.mutex.Mutex.lock_nothrow!(core.sync.mutex.Mutex)() nothrow @nogc @trustedIf this lock is not already held by the caller, the lock is acquired,
then the internal counter is incremented by one.
Note
Mutex.lock does not throw, but a class derived from Mutex can throw.
Use lock_nothrow in nothrow @nogc code.
lock_nothrow();
void void mutex_throughput.Pthread.unlock() nothrow @nogc @systemunlock() @system nothrow @nogc => (__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.mm.void core.sync.mutex.Mutex.unlock_nothrow!(core.sync.mutex.Mutex)() nothrow @nogc @trustedDecrements the internal lock count by one. If this brings the count to
zero, the lock is released.
Note
Mutex.unlock does not throw, but a class derived from Mutex can throw.
Use unlock_nothrow in nothrow @nogc code.
unlock_nothrow();
}
/// A test-and-test-and-set spin lock with backoff.
struct (struct) mutex_throughput.TtasA test-and-test-and-set spin lock with backoff.
Ttas
{
shared uint (field) shared(uint) mutex_throughput.Ttas.statestate;
void void mutex_throughput.Ttas.lock() nothrow @nogc @systemlock() @system nothrow @nogc
{
uint (local variable) uint roundround;
while (true)
{
if (!uint core.atomic.atomicLoad!(MemoryOrder.seq, uint)(ref return scope shared(const(uint)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((field) shared(uint) mutex_throughput.Ttas.statestate) && bool core.atomic.cas!().cas!(uint, uint, uint)(shared(uint)* here, uint ifThis, uint writeThis) pure nothrow @nogc @trustedPerforms 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.
cas(&(field) shared(uint) mutex_throughput.Ttas.statestate, 0u, 1u))
return;
if (++(local variable) uint roundround < 64)
foreach ((local variable) int __; 0 .. 1 << ((local variable) uint roundround < 8 ? (local variable) uint roundround : 8))
void core.atomic.pause() pure nothrow @nogc @safeGives 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 @nogcsched_yield();
}
}
void void mutex_throughput.Ttas.unlock() nothrow @nogc @systemunlock() @system nothrow @nogc => void core.atomic.atomicStore!(MemoryOrder.seq, uint, uint)(ref shared(uint) val, uint newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((field) shared(uint) mutex_throughput.Ttas.statestate, 0u);
}
struct (struct) mutex_throughput.ResultResult
{
double (field) double mutex_throughput.Result.opsPerUsopsPerUs;
double (field) double mutex_throughput.Result.fairnessfairness;
double (field) double mutex_throughput.Result.wakesPerOpwakesPerOp, (field) double mutex_throughput.Result.waitsPerOpwaitsPerOp;
}
/// Runs `threads` threads against one `L` for `ms` milliseconds.
(struct) mutex_throughput.ResultResult mutex_throughput.Result mutex_throughput.run!(mutex_throughput.Futex3)(uint threads, uint ms) @systemRuns threads threads against one L for ms milliseconds.
run(L)(uint (parameter) uint threadsthreads, uint (parameter) uint msms) @system
{
static if (is((alias) L = mutex_throughput.Futex3L == Pthread))
{
import (package) corecore.(package) core.syncsync.(module) core.sync.mutexThe mutex module provides a primitive for maintaining mutually exclusive
access.
Source
core/sync/mutex.d
mutex : (class) core.sync.mutex.MutexThis class represents a general purpose, recursive mutex.
Implemented using pthread_mutex on Posix and CRITICAL_SECTION
on Windows.
Examples
import core.thread : Thread;
class Resource
{
Mutex mtx;
int cargo;
this() shared @safe nothrow
{
mtx = new shared Mutex();
cargo = 42;
}
void useResource() shared @trusted nothrow @nogc
{
mtx.lock_nothrow();
(cast() cargo) += 1;
mtx.unlock_nothrow();
}
}
shared Resource res = new shared Resource();
auto otherThread = new Thread(
{
foreach (i; 0 .. 10000)
res.useResource();
}).start();
foreach (i; 0 .. 10000)
res.useResource();
otherThread.join();
assert (res.cargo == 20042);
Mutex;
(struct) mutex_throughput.Pthreaddruntime's mutex, a pthread_mutex_t.
Pthread.(__gshared global) core.sync.mutex.Mutex mutex_throughput.Pthread.mm = new (class) core.sync.mutex.MutexThis class represents a general purpose, recursive mutex.
Implemented using pthread_mutex on Posix and CRITICAL_SECTION
on Windows.
Examples
import core.thread : Thread;
class Resource
{
Mutex mtx;
int cargo;
this() shared @safe nothrow
{
mtx = new shared Mutex();
cargo = 42;
}
void useResource() shared @trusted nothrow @nogc
{
mtx.lock_nothrow();
(cast() cargo) += 1;
mtx.unlock_nothrow();
}
}
shared Resource res = new shared Resource();
auto otherThread = new Thread(
{
foreach (i; 0 .. 10000)
res.useResource();
}).start();
foreach (i; 0 .. 10000)
res.useResource();
otherThread.join();
assert (res.cargo == 20042);
Mutex;
}
__gshared (alias) L = mutex_throughput.Futex3L (__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).locklock;
__gshared ulong (__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).guardedguarded; // only touched under the lock
__gshared ulong (__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).insideinside; // a plain counter: a lost update means a broken lock
static shared ulong (shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).sinksink;
static shared bool (shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stopstop;
static shared ulong (shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakeswakes, (shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waitswaits;
void core.atomic.atomicStore!(MemoryOrder.seq, ulong, ulong)(ref shared(ulong) val, ulong newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakeswakes, 0UL);
void core.atomic.atomicStore!(MemoryOrder.seq, ulong, ulong)(ref shared(ulong) val, ulong newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waitswaits, 0UL);
(__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).locklock = (struct) mutex_throughput.Futex3The 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).guardedguarded = 0;
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).insideinside = 0;
void core.atomic.atomicStore!(MemoryOrder.seq, bool, bool)(ref shared(bool) val, bool newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stopstop, false);
auto (local variable) ulong[] countscounts = new ulong[(parameter) uint threadsthreads];
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread[] (local variable) core.thread.osthread.Thread[] workersworkers;
// 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.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread core.thread.osthread.Thread mutex_throughput.run!(mutex_throughput.Futex3).worker(uint id) pure nothrow @safeworker(uint (parameter) uint idid)
{
return new (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread({
ulong (local variable) ulong nn, (local variable) ulong locallocal = (parameter) uint idid;
while (!bool core.atomic.atomicLoad!(MemoryOrder.seq, bool)(ref return scope shared(const(bool)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stopstop))
{
(__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).locklock.void mutex_throughput.Futex3.lock() nothrow @nogc @systemlock();
// A short critical section: a few dependent updates.
foreach ((local variable) int __; 0 .. 8)
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).guardedguarded = (__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).guardedguarded * 6_364_136_223_846_793_005UL + 1;
++(local variable) ulong nn;
(__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).insideinside = (__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).insideinside + 1;
(__gshared global) mutex_throughput.Futex3 mutex_throughput.run!(mutex_throughput.Futex3).locklock.void mutex_throughput.Futex3.unlock() nothrow @nogc @systemunlock();
// A little work outside the lock.
foreach ((local variable) int __; 0 .. 16)
(local variable) ulong locallocal = (local variable) ulong locallocal * 2_862_933_555_777_941_757UL + 3_037_000_493UL;
}
(local variable) ulong[] countscounts[(parameter) uint idid] = (local variable) ulong nn;
ulong core.atomic.atomicOp!("+=", ulong, ulong)(ref shared(ulong) val, ulong mod) pure nothrow @nogc @safePerforms the binary operation 'op' on val using 'mod' as the modifier.
atomicOp!"+="((shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).sinksink, (local variable) ulong locallocal); // keep `local` alive
ulong core.atomic.atomicOp!("+=", ulong, ulong)(ref shared(ulong) val, ulong mod) pure nothrow @nogc @safePerforms the binary operation 'op' on val using 'mod' as the modifier.
atomicOp!"+="((shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakeswakes, (thread local global) ulong mutex_throughput.wakeCallsWait 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 @safePerforms the binary operation 'op' on val using 'mod' as the modifier.
atomicOp!"+="((shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waitswaits, (thread local global) ulong mutex_throughput.waitCallsWait 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 tt; 0 .. (parameter) uint threadsthreads)
(local variable) core.thread.osthread.Thread[] workersworkers ~= core.thread.osthread.Thread mutex_throughput.run!(mutex_throughput.Futex3).worker(uint id) pure nothrow @safeworker((local variable) uint tt);
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) startstart = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime;
foreach ((parameter) core.thread.osthread.Thread ww; (local variable) core.thread.osthread.Thread[] workersworkers)
(local variable) core.thread.osthread.Thread ww.core.thread.osthread.Thread core.thread.osthread.Thread.start() nothrowStarts the thread and invokes the function or delegate passed upon
construction.
In
This routine may only be called once per thread instance.
start();
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends 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
sleep((parameter) uint msms.msecs);
void core.atomic.atomicStore!(MemoryOrder.seq, bool, bool)(ref shared(bool) val, bool newval) pure nothrow @nogc @trustedWrites 'newval' into 'val'. The memory barrier specified by 'ms' is
applied to the operation, which is fully sequenced by default.
Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
MemoryOrder.seq.
atomicStore((shared global) shared(bool) mutex_throughput.run!(mutex_throughput.Futex3).stopstop, true);
foreach ((parameter) core.thread.osthread.Thread ww; (local variable) core.thread.osthread.Thread[] workersworkers)
(local variable) core.thread.osthread.Thread ww.object.Throwable core.thread.osthread.Thread.join(bool rethrow = true)Waits for this thread to complete. If the thread terminated as the
result of an unhandled exception, this exception will be rethrown.
join();
const (local variable) const(long) usus = ((struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime - core.time.Duration core.time.MonoTimeImpl!(ClockType.normal).opBinary!"-"(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeSubtracting two MonoTimes results in a Duration representing
the amount of time which elapsed between them.
The primary way that programs should time how long something takes is to
do
MonoTime before = MonoTime.currTime;
// do stuff
MonoTime after = MonoTime.currTime;
// How long it took.
Duration timeElapsed = after - before;
or to use a wrapper (such as a stop watch type) which does that.
Warning:
Because Duration is in hnsecs, whereas MonoTime is in system
ticks, it's usually the case that this assertion will fail
auto before = MonoTime.currTime;
// do stuff
auto after = MonoTime.currTime;
auto timeElapsed = after - before;
assert(before + timeElapsed == after);
This is generally fine, and by its very nature, converting from
system ticks to any type of seconds (hnsecs, nsecs, etc.) will
introduce rounding errors, but if code needs to avoid any of the
small rounding errors introduced by conversion, then it needs to use
MonoTime's ticks property and keep all calculations in ticks
rather than using Duration.
start).long core.time.Duration.total!"usecs"() const pure nothrow @nogc @property @safeReturns the total number of the given units in this Duration.
So, unlike split, it does not strip out the larger units.
Examples
assert(dur!"weeks"(12).total!"weeks" == 12);
assert(dur!"weeks"(12).total!"days" == 84);
assert(dur!"days"(13).total!"weeks" == 1);
assert(dur!"days"(13).total!"days" == 13);
assert(dur!"hours"(49).total!"days" == 2);
assert(dur!"hours"(49).total!"hours" == 49);
assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
total!"usecs";
assert((__gshared global) ulong mutex_throughput.run!(mutex_throughput.Futex3).insideinside == (local variable) ulong[] countscounts.ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safeSums 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.
sum, (struct) mutex_throughput.Futex3The three-state futex mutex.
L.(constant) string mutex_throughput.Futex3.stringof = "Futex3"stringof ~ " let two threads into the critical section");
return (struct) mutex_throughput.ResultResult((local variable) ulong[] countscounts.ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safeSums 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.
sum / cast(double) (local variable) const(long) usus,
(local variable) ulong[] countscounts.ulong std.algorithm.searching.minElement!((a) => a, ulong[])(ulong[] r) pure nothrow @nogc @safeIterates 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);
minElement / cast(double) (local variable) ulong[] countscounts.ulong std.algorithm.searching.maxElement!((a) => a, ulong[])(ulong[] r) pure nothrow @nogc @safeIterates 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.
maxElement,
ulong core.atomic.atomicLoad!(MemoryOrder.seq, ulong)(ref return scope shared(const(ulong)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).wakeswakes) / cast(double) (local variable) ulong[] countscounts.ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safeSums 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.
sum,
ulong core.atomic.atomicLoad!(MemoryOrder.seq, ulong)(ref return scope shared(const(ulong)) val) pure nothrow @nogc @trustedLoads 'val' from memory and returns it. The memory barrier specified
by 'ms' is applied to the operation, which is fully sequenced by
default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
and MemoryOrder.seq.
atomicLoad((shared global) shared(ulong) mutex_throughput.run!(mutex_throughput.Futex3).waitswaits) / cast(double) (local variable) ulong[] countscounts.ulong std.algorithm.iteration.sum!(ulong[])(ulong[] r) pure nothrow @nogc @safeSums 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.
sum);
}
void void D main() @systemmain() @system
{
const (local variable) immutable(uint) corescores = totalCPUs;
uint[] (local variable) uint[] threadCountsthreadCounts = [1, 2, 4];
if ((local variable) immutable(uint) corescores > 4)
(local variable) uint[] threadCountsthreadCounts ~= (local variable) immutable(uint) corescores;
(local variable) uint[] threadCountsthreadCounts ~= 2 * (local variable) immutable(uint) corescores; // oversubscribed
enum uint (constant) uint mutex_throughput.main.ms = 100ums = 100;
void std.stdio.writefln!(char, immutable(uint), uint)(in char[] fmt, immutable(uint) __param_1, uint __param_2) @safeEquivalent 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) corescores, (constant) uint mutex_throughput.main.ms = 100ums);
void std.stdio.writefln!(char, string, string)(in char[] fmt, string __param_1, string __param_2) @safeEquivalent 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 @safeExamples
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 nn; (local variable) uint[] threadCountsthreadCounts)
{
(alias) object.string = stringstring (local variable) string rowrow;
static foreach (L; [`Futex3`, `Parking`, `ParkingDesig`, `Pthread`, `Ttas`])
{{
const (local variable) const(mutex_throughput.Result) rr = mutex_throughput.Result mutex_throughput.run!(mutex_throughput.Futex3)(uint threads, uint ms) @systemRuns threads threads against one L for ms milliseconds.
run!(mixin(L))((local variable) uint nn, (constant) uint mutex_throughput.main.ms = 100ums);
(local variable) string rowrow ~= ((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 @safeExamples
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 @safeExamples
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) rr.(field) double mutex_throughput.Result.opsPerUsopsPerUs, (local variable) const(mutex_throughput.Result) rr.(field) double mutex_throughput.Result.fairnessfairness))
: string std.format.format!("%-28s", string)(string __param_0) pure @safeExamples
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 @safeExamples
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) rr.(field) double mutex_throughput.Result.opsPerUsopsPerUs, (local variable) const(mutex_throughput.Result) rr.(field) double mutex_throughput.Result.fairnessfairness,
(local variable) const(mutex_throughput.Result) rr.(field) double mutex_throughput.Result.waitsPerOpwaitsPerOp, (local variable) const(mutex_throughput.Result) rr.(field) double mutex_throughput.Result.wakesPerOpwakesPerOp)));
}}
void std.stdio.writefln!(char, string, string)(in char[] fmt, string __param_1, string __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln("%-9s%s", (local variable) uint nn == 2 * (local variable) immutable(uint) corescores ? string std.format.format!("%u*", uint)(uint __param_0) pure @safeExamples
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 nn) : string std.format.format!("%u", uint)(uint __param_0) pure @safeExamples
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 nn), (local variable) string rowrow);
}
void std.stdio.writeln!string(string __param_0) @safeEquivalent 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);
}
}
writeln("* oversubscribed: more threads than hardware threads");
}