The thread module provides support for thread creation and management.
Returns the process ID of the calling process, which is guaranteed to be unique on the system. This call is always successful.
writefln("Current process id: %s", getpid());
Base class for thread exceptions.
Base class for thread errors to be used for function inside GC when allocations are unavailable.
This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.
class DerivedThread : Thread { this() { super(&run); } private: void run() { // Derived thread running. } } void threadFunc() { // Composed thread running. } // create and start instances of each type auto derived = new DerivedThread().start(); auto composed = new Thread(&threadFunc).start(); new Thread({ // Codes to run in the newly created thread. }).start();
Initializes a thread object which is associated with a static D function.
void function() fn
| The thread function. |
size_t sz
| The stack size for this thread. |
Initializes a thread object which is associated with a dynamic D function.
void delegate() dg
| The thread function. |
size_t sz
| The stack size for this thread. |
Starts the thread and invokes the function or delegate passed upon construction.
Waits for this thread to complete. If the thread terminated as the result of an unhandled exception, this exception will be rethrown.
bool rethrow
| Rethrow any unhandled exception which may have caused this thread to terminate. |
Gets the OS identifier for this thread.
ThreadID
.init
. Otherwise, returns the result of GetCurrentThreadId
on Windows, and pthread_self
on POSIX. The value is unique for the current process.Gets the user-readable label for this thread.
Sets the user-readable label for this thread.
string val
| The new name of this thread. |
Gets the daemon status for this thread. While the runtime will wait for all normal threads to complete before tearing down the process, daemon threads are effectively ignored and thus will not prevent the process from terminating. In effect, daemon threads will be terminated automatically by the OS when the process exits.
Sets the daemon status for this thread. While the runtime will wait for all normal threads to complete before tearing down the process, daemon threads are effectively ignored and thus will not prevent the process from terminating. In effect, daemon threads will be terminated automatically by the OS when the process exits.
bool val
| The new daemon status for this thread. |
Tests whether this thread is the main thread, i.e. the thread that initialized the runtime
Tests whether this thread is running.
The minimum scheduling priority that may be set for a thread. On systems where multiple scheduling policies are defined, this value represents the minimum valid priority for the scheduling policy of the process.
The maximum scheduling priority that may be set for a thread. On systems where multiple scheduling policies are defined, this value represents the maximum valid priority for the scheduling policy of the process.
The default scheduling priority that is set for a thread. On systems where multiple scheduling policies are defined, this value represents the default priority for the scheduling policy of the process.
Gets the scheduling priority for the associated thread.
Sets the scheduling priority for the associated thread.
int val
| The new scheduling priority of this thread. |
Suspends the calling thread for at least the supplied period. This may result in multiple OS calls if period is greater than the maximum sleep duration supported by the operating system.
Duration val
| The minimum duration the calling thread should be suspended. |
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
Forces a context switch to occur away from the calling thread.
Provides a reference to the calling thread.
Provides a list of all threads currently being tracked by the system. Note that threads in the returned array might no longer run (see Thread.
isRunning
).
Operates on all threads currently being tracked by the system. The result of deleting any Thread object is undefined. Note that threads passed to the callback might no longer run (see Thread.
isRunning
).
int delegate(ref Thread) dg
| The supplied code as a delegate. |
Instruct the thread module, when initialized, to use a different set of signals besides SIGUSR1 and SIGUSR2 for suspension and resumption of threads. This function should be called at most once, prior to thread_init(). This function is Posix-only.
Initializes the thread module. This function must be called by the garbage collector on startup and before any other thread routines are called.
Terminates the thread module. No other thread routine may be called afterwards.
Registers the calling thread for use with the D Runtime. If this routine is called for a thread which is already registered, no action is performed.
Deregisters the calling thread from use with the runtime. If this routine is called for a thread which is not registered, the result is undefined.
extern(C) void rt_moduleTlsDtor();
Deregisters the given thread from use with the runtime. If this routine is called for a thread which is not registered, the result is undefined.
extern(C) void rt_moduleTlsDtor();
Search the list of all threads for a thread with the given thread identifier.
ThreadID addr
| The thread identifier to search for. |
Sets the current thread to a specific reference. Only to be used when dealing with externally-created threads (in e.g. C code). The primary use of this function is when Thread.getThis() must return a sensible value in, for example, TLS destructors. In other words, don't touch this unless you know what you're doing.
Thread t
| A reference to the current thread. May be null. |
Joins all non-daemon threads that are currently running. This is done by performing successive scans through the thread list until a scan consists of only daemon threads.
Suspend all threads but the calling thread for "stop the world" garbage collection runs. This function may be called multiple times, and must be followed by a matching number of calls to thread_resumeAll before processing is resumed.
Resume all threads but the calling thread for "stop the world" garbage collection runs. This function must be called once for each preceding call to thread_suspendAll before the threads are actually resumed.
Indicates the kind of scan being performed by thread_scanAllType
.
The stack and/or registers are being scanned.
TLS data is being scanned.
The scanning function.
The main entry point for garbage collection. The supplied delegate will be passed ranges representing both stack and register values.
ScanAllThreadsTypeFn scan
| The scanner function. It should scan from p1 through p2 - 1. |
The main entry point for garbage collection. The supplied delegate will be passed ranges representing both stack and register values.
ScanAllThreadsFn scan
| The scanner function. It should scan from p1 through p2 - 1. |
Signals that the code following this call is a critical region. Any code in this region must finish running before the calling thread can be suspended by a call to thread_suspendAll.
This function is, in particular, meant to help maintain garbage collector invariants when a lock is not used.
A critical region is exited with thread_exitCriticalRegion.
Warning: Using critical regions is extremely error-prone. For instance, using locks inside a critical region can easily result in a deadlock when another thread holding the lock already got suspended.
The term and concept of a 'critical region' comes from Mono's SGen garbage collector.
Signals that the calling thread is no longer in a critical region. Following a call to this function, the thread can once again be suspended.
Returns true if the current thread is in a critical region; otherwise, false.
Indicates whether an address has been marked by the GC.
Address is not marked.
Address is marked.
Address is not managed by the GC.
The isMarked callback function.
This routine allows the runtime to process any special per-thread handling for the GC. This is needed for taking into account any memory that is referenced by non-scanned pointers but is about to be freed. That currently means the array append cache.
IsMarkedDg isMarked
| The function used to check if addr is marked. |
Returns the stack top of the currently active stack within the calling thread.
Returns the stack bottom of the currently active stack within the calling thread.
This class is intended to simplify certain common programming techniques.
Creates and starts a new Thread object that executes fn and adds it to the list of tracked threads.
void function() fn
| The thread function. |
Creates and starts a new Thread object that executes dg and adds it to the list of tracked threads.
void delegate() dg
| The thread function. |
Add t to the list of tracked threads if it is not already being tracked.
Thread t
| The thread to add. |
Removes t from the list of tracked threads. No operation will be performed if t is not currently being tracked by this object.
Thread t
| The thread to remove. |
Operates on all threads currently tracked by this object.
Iteratively joins all tracked threads. This function will block add, remove, and opApply until it completes.
bool rethrow
| Rethrow any unhandled exception which may have caused the current thread to terminate. |
This class provides a cooperative concurrency mechanism integrated with the threading and garbage collection functionality. Calling a fiber may be considered a blocking operation that returns when the fiber yields (via Fiber.yield()). Execution occurs within the context of the calling thread so synchronization is not necessary to guarantee memory visibility so long as the same thread calls the fiber each time. Please note that there is no requirement that a fiber be bound to one specific thread. Rather, fibers may be freely passed between threads so long as they are not currently executing. Like threads, a new fiber thread may be created using either derivation or composition, as in the following example.
int counter; class DerivedFiber : Fiber { this() { super( &run ); } private : void run() { counter += 2; } } void fiberFunc() { counter += 4; Fiber.yield(); counter += 8; } // create instances of each type Fiber derived = new DerivedFiber(); Fiber composed = new Fiber( &fiberFunc ); assert( counter == 0 ); derived.call(); assert( counter == 2, "Derived fiber increment." ); composed.call(); assert( counter == 6, "First composed fiber increment." ); counter += 16; assert( counter == 22, "Calling context increment." ); composed.call(); assert( counter == 30, "Second composed fiber increment." ); // since each fiber has run to completion, each should have state TERM assert( derived.state == Fiber.State.TERM ); assert( composed.state == Fiber.State.TERM );
Initializes a fiber object which is associated with a static D function.
void function() fn
| The fiber function. |
size_t sz
| The stack size for this fiber. |
size_t guardPageSize
| size of the guard page to trap fiber's stack overflows. Beware that using this will increase the number of mmaped regions on platforms using mmap so an OS-imposed limit may be hit. |
Initializes a fiber object which is associated with a dynamic D function.
void delegate() dg
| The fiber function. |
size_t sz
| The stack size for this fiber. |
size_t guardPageSize
| size of the guard page to trap fiber's stack overflows. Beware that using this will increase the number of mmaped regions on platforms using mmap so an OS-imposed limit may be hit. |
Transfers execution to this fiber object. The calling context will be suspended until the fiber calls Fiber.yield() or until it terminates via an unhandled exception.
Rethrow rethrow
| Rethrow any unhandled exception which may have caused this fiber to terminate. |
Flag to control rethrow behavior of call
Resets this fiber so that it may be re-used, optionally with a new function/delegate. This routine should only be called for fibers that have terminated, as doing otherwise could result in scope-dependent functionality that is not executed. Stack-based classes, for example, may not be cleaned up properly if a fiber is reset before it has terminated.
A fiber may occupy one of three states: HOLD, EXEC, and TERM.
The HOLD state applies to any fiber that is suspended and ready to be called.
The EXEC state will be set for any fiber that is currently executing.
The TERM state is set when a fiber terminates. Once a fiber terminates, it must be reset before it may be called again.
Gets the current state of this fiber.
Forces a context switch to occur away from the calling fiber.
Forces a context switch to occur away from the calling fiber and then throws obj in the calling fiber.
Throwable t
| The object to throw. |
Provides a reference to the calling fiber or null if no fiber is currently active.
Represents the ID of a thread, as returned by Thread.
id
. The exact type varies from platform to platform.
Create a thread not under control of the runtime, i.e. TLS module constructors are not run and the GC does not suspend it during a collection.
void delegate() nothrow dg
| delegate to execute in the created thread. |
uint stacksize
| size of the stack of the created thread. The default of 0 will select the platform-specific default size. |
void delegate() nothrow cbDllUnload
| Windows only: if running in a dynamically loaded DLL, this delegate will be called if the DLL is supposed to be unloaded, but the thread is still running. The thread must be terminated via joinLowLevelThread by the callback. |
ThreadID.init
is returned.Wait for a thread created with createLowLevelThread
to terminate.
ThreadID tid
| the thread ID returned by createLowLevelThread . |
Check whether a thread was created by createLowLevelThread
.
ThreadID tid
| the platform specific thread ID. |
true
if the thread was created by createLowLevelThread
and is still running.
© 1999–2019 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/core_thread.html