tango.core.Thread

The thread module provides support for thread creation and management.

License:

BSD style: see license.txt

Authors:

Sean Kelly
class Thread #
This class encapsulates all threading functionality for the D programming language. As thread manipulation is a required facility for garbage collection, all user threads should derive from this class, and instances of this class should never be explicitly deleted. A new thread may be created using either derivation or composition, as in the following example.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class DerivedThread : Thread
{
    this()
    {
        super( &run );
    }

private :
    void run()
    {
        printf( "Derived thread running.\n" );
    }
}

void threadFunc()
{
    printf( "Composed thread running.\n" );
}

// create instances of each type
Thread derived = new DerivedThread();
Thread composed = new Thread( &threadFunc );

// start both threads
derived.start();
composed.start();
this(void function() fn, size_t sz = 0) #
Initializes a thread object which is associated with a static D function.

Params:

fnThe thread function.
szThe stack size for this thread.

In:

fn must not be null.
this(void delegate() dg, size_t sz = 0) #
Initializes a thread object which is associated with a dynamic D function.

Params:

dgThe thread function.
szThe stack size for this thread.

In:

dg must not be null.
~this() #
Cleans up any remaining resources used by this object.
void start() [final] #
Starts the thread and invokes the function or delegate passed upon construction.

In:

This routine may only be called once per thread instance.

Throws:

ThreadException if the thread fails to start.
Object join(bool rethrow = true) [final] #
Waits for this thread to complete. If the thread terminated as the result of an unhandled exception, this exception will be rethrown.

Params:

rethrowRethrow any unhandled exception which may have caused this thread to terminate.

Throws:

ThreadException if the operation fails. Any exception not handled by the joined thread.

Returns:

Any exception not handled by this thread if rethrow = false, null otherwise.
char[] name() [final] #
Gets the user-readable label for this thread.

Returns:

The name of this thread.
void name(char[] val) [final] #
Sets the user-readable label for this thread.

Params:

valThe new name of this thread.
bool isDaemon() [final] #
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.

Returns:

true if this is a daemon thread.
void isDaemon(bool val) [final] #
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.

Params:

valThe new daemon status for this thread.
bool isRunning() [final] #
Tests whether this thread is running.

Returns:

true if the thread is running, false if not.
int PRIORITY_MIN [static, const] #
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.
int PRIORITY_MAX [static, const] #
The maximum 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.
int priority() [final] #
Gets the scheduling priority for the associated thread.

Returns:

The scheduling priority of this thread.
void priority(int val) [final] #
Sets the scheduling priority for the associated thread.

Params:

valThe new scheduling priority of this thread.
void sleep(double period) [static] #
Suspends the calling thread for at least the supplied time, up to a maximum of (uint.max - 1) milliseconds.

Params:

periodThe minimum duration the calling thread should be suspended, in seconds. Sub-second durations are specified as fractional values.

In:

period must be less than (uint.max - 1) milliseconds.

Example:

1
2
3
4
Thread.sleep( 0.05 ); // sleep for 50 milliseconds
Thread.sleep( 5 );    // sleep for 5 seconds
void yield() [static] #
Forces a context switch to occur away from the calling thread.
Thread getThis() [static] #
Provides a reference to the calling thread.

Returns:

The thread object representing the calling thread. The result of deleting this object is undefined.
Thread[] getAll() [static] #
Provides a list of all threads currently being tracked by the system.

Returns:

An array containing references to all threads currently being tracked by the system. The result of deleting any contained objects is undefined.
int opApply(int delegate( ref Thread ) dg) [static] #
Operates on all threads currently being tracked by the system. The result of deleting any Thread object is undefined.

Params:

dgThe supplied code as a delegate.

Returns:

Zero if all elemented are visited, nonzero if not.
uint LOCAL_MAX [static, const] #
Indicates the number of local storage pointers available at program startup. It is recommended that this number be at least 64.
uint createLocal() [static] #
Reserves a local storage pointer for use and initializes this location to null for all running threads.

Returns:

A key representing the array offset of this memory location.
void deleteLocal(uint key) [static] #
Marks the supplied key as available and sets the associated location to null for all running threads. It is assumed that any key passed to this function is valid. The result of calling this function for a key which is still in use is undefined.

Params:

keyThe key to delete.
void* getLocal(uint key) [static] #
Loads the value stored at key within a thread-local static array. It is assumed that any key passed to this function is valid.

Params:

keyThe location which holds the desired data.

Returns:

The data associated with the supplied key.
void* setLocal(uint key, void* val) [static] #
Stores the supplied value at key within a thread-local static array. It is assumed that any key passed to this function is valid.

Params:

keyThe location to store the supplied data.
valThe data to store.

Returns:

A copy of the data which has just been stored.
static this() #
This initializer is used to set thread constants. All functional initialization occurs within thread_init().
void setThis(Thread t) [private, static] #
void pushContext(Context* c) [private, final] #
Object slock() [private, static] #
void add(Context* c) [private, static] #
void add(Thread t) [private, static] #
void thread_init() [extern(C)] #
Initializes the thread module. This function must be called by the garbage collector on startup and before any other thread routines are called.
void thread_attachThis() [extern(C)] #
Registers the calling thread for use with Tango. If this routine is called for a thread which is already registered, the result is undefined.
void thread_detachThis() [extern(C)] #
Deregisters the calling thread from use with Tango. If this routine is called for a thread which is already registered, the result is undefined.
void thread_joinAll() [extern(C)] #
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.
static ~this() #
Performs intermediate shutdown of the thread module.
bool thread_needLock() [extern(C)] #
This function is used to determine whether the the process is multi-threaded. Optimizations may only be performed on this value if the programmer can guarantee that no path from the enclosed code will start a thread.

Returns:

True if Thread.start() has been called in this process.
void thread_suspendAll() [extern(C)] #
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.

Throws:

ThreadException if the suspend operation fails for a running thread.
void thread_resumeAll() [extern(C)] #
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.

In:

This routine must be preceded by a call to thread_suspendAll.

Throws:

ThreadException if the resume operation fails for a running thread.
void thread_scanAll(scanAllThreadsFn scan, void* curStackTop = null) [extern(C)] #
The main entry point for garbage collection. The supplied delegate will be passed ranges representing both stack and register values.

Params:

scanThe scanner function. It should scan from p1 through p2 - 1.
curStackTopAn optional pointer to the top of the calling thread's stack.

In:

This routine must be preceded by a call to thread_suspendAll.
class ThreadLocal(T) #
This class encapsulates the operations required to initialize, access, and destroy thread local data.
this(T def = T.init) #
Initializes thread local storage for the indicated value which will be initialized to def for all threads.

Params:

defThe default value to return if no value has been explicitly set.
T val() #
Gets the value last set by the calling thread, or def if no such value has been set.

Returns:

The stored value or def if no value is stored.
T val(T newval) #
Copies newval to a location specific to the calling thread, and returns newval.

Params:

newvalThe value to set.

Returns:

The value passed to this function.
class ThreadGroup #
This class is intended to simplify certain common programming techniques.
Thread create(void function() fn) [final] #
Creates and starts a new Thread object that executes fn and adds it to the list of tracked threads.

Params:

fnThe thread function.

Returns:

A reference to the newly created thread.
Thread create(void delegate() dg) [final] #
Creates and starts a new Thread object that executes dg and adds it to the list of tracked threads.

Params:

dgThe thread function.

Returns:

A reference to the newly created thread.
void add(Thread t) [final] #
Add t to the list of tracked threads if it is not already being tracked.

Params:

tThe thread to add.

In:

t must not be null.
void remove(Thread t) [final] #
Removes t from the list of tracked threads. No operation will be performed if t is not currently being tracked by this object.

Params:

tThe thread to remove.

In:

t must not be null.
int opApply(int delegate( ref Thread ) dg) [final] #
Operates on all threads currently tracked by this object.
void joinAll(bool rethrow = true) [final] #
Iteratively joins all tracked threads. This function will block add, remove, and opApply until it completes.

Params:

rethrowRethrow any unhandled exception which may have caused the current thread to terminate.

Throws:

Any exception not handled by the joined threads.
class Fiber #
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.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class DerivedFiber : Fiber
{
    this()
    {
        super( &run );
    }

private :
    void run()
    {
        printf( "Derived fiber running.\n" );
    }
}

void fiberFunc()
{
    printf( "Composed fiber running.\n" );
    Fiber.yield();
    printf( "Composed fiber running.\n" );
}

// create instances of each type
Fiber derived = new DerivedFiber();
Fiber composed = new Fiber( &fiberFunc );

// call both fibers once
derived.call();
composed.call();
printf( "Execution returned to calling context.\n" );
composed.call();

// since each fiber has run to completion, each should have state TERM
assert( derived.state == Fiber.State.TERM );
assert( composed.state == Fiber.State.TERM );

Authors:

Based on a design by Mikola Lysenko.
this(void function() fn, size_t sz = PAGESIZE) #
Initializes a fiber object which is associated with a static D function.

Params:

fnThe thread function.
szThe stack size for this fiber.

In:

fn must not be null.
this(void delegate() dg, size_t sz = PAGESIZE, Scheduler s = null) #
Initializes a fiber object which is associated with a dynamic D function.

Params:

dgThe thread function.
szThe stack size for this fiber.

In:

dg must not be null.
~this() #
Cleans up any remaining resources used by this object.
Object call(bool rethrow = true) [final] #
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.

Params:

rethrowRethrow any unhandled exception which may have caused this fiber to terminate.

In:

This fiber must be in state HOLD.

Throws:

Any exception not handled by the joined thread.

Returns:

Any exception not handled by this fiber if rethrow = false, null otherwise.
void reset() [final] #
Resets this fiber so that it may be re-used with the same function. This routine may 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.

In:

This fiber must be in state TERM, and have a valid function/delegate.
void reset(void function() fn) [final] #
Reinitializes a fiber object which is associated with a static D function.

Params:

fnThe thread function.

In:

This fiber must be in state TERM. fn must not be null.
void reset(void delegate() dg) [final] #
reinitializes a fiber object which is associated with a dynamic D function.

Params:

dgThe thread function.

In:

This fiber must be in state TERM. dg must not be null.
void clear() [final] #
Clears the fiber from all references to a previous call (unhandled exceptions, delegate)

In:

This fiber must be in state TERM.
enum State #
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. And the TERM state is set when a fiber terminates. Once a fiber terminates, it must be reset before it may be called again.
HOLD #
EXEC #
TERM #
State state() [final] #
Gets the current state of this fiber.

Returns:

The state of this fiber as an enumerated value.
void cede() [final] #
Forces a context switch to occur away from the calling fiber.
void yield() [static] #
Forces a context switch to occur away from the calling fiber.
void yieldAndThrow(Object obj) [static] #
Forces a context switch to occur away from the calling fiber and then throws obj in the calling fiber.

Params:

objThe object to throw.

In:

obj must not be null.
Fiber getThis() [static] #
Provides a reference to the calling fiber or null if no fiber is currently active.

Returns:

The fiber object representing the calling fiber or null if no fiber is currently active. The result of deleting this object is undefined.
static this() #
void allocStack(size_t sz) [private, final] #
void setThis(Fiber f) [private, static] #
void switchIn() [private, final] #