D Programming Language 2.0

- Comments
- D
- Search
- Home

Last update Thu Oct 28 17:54:37 2010

# core.thread

The thread module provides support for thread creation and management.

License:
Boost License 1.0.

Authors:
Sean Kelly, Walter Bright

Copyright Sean Kelly 2005 - 2009. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at

http:
//www.boost.org/LICENSE_1_0.txt)

Source:
http://www.dsource.org/projects/druntime/browser/trunk/src/core/thread.d

class ThreadException: object.Exception;
  Base class for thread exceptions.

class FiberException: object.Exception;
  Base class for fiber exceptions.

alias btex_fptr;

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:

       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.

    Parameters:

    void function() fn | The thread function.
    size_t sz | The 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.

    Parameters:

    void delegate() dg | The thread function.
    size_t sz | The stack size for this thread.

    In:
    dg must not be null.

  final void start();
    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.

  final Throwable 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.

    Parameters:

    bool rethrow | Rethrow 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.

  final string name();
    Gets the user-readable label for this thread.

    Returns:
    The name of this thread.

  final void name(string val);
    Sets the user-readable label for this thread.

    Parameters:

    string val | The new name of this thread.

  final bool isDaemon();
    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.

  final void isDaemon(bool val);
    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.

    Parameters:

    bool val | The new daemon status for this thread.

  final bool isRunning();
    Tests whether this thread is running.

    Returns:
    true if the thread is running, false if not.

  const int PRIORITY_MIN;
    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.

  const int PRIORITY_MAX;
    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.

  final int priority();
    Gets the scheduling priority for the associated thread.

    Returns:
    The scheduling priority of this thread.

  final void priority(int val);
    Sets the scheduling priority for the associated thread.

    Parameters:

    int val | The new scheduling priority of this thread.

  static void sleep(long period);
    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.

    Parameters:

    long period | The minimum duration the calling thread should be suspended, in 100 nanosecond intervals.

    In:
    period must be non-negative.

    Example:

         Thread.sleep( 500_000 );    // sleep for 50 milliseconds
         Thread.sleep( 50_000_000 ); // sleep for 5 seconds

  static void yield();
    Forces a context switch to occur away from the calling thread.

  static Thread getThis();
    Provides a reference to the calling thread.

    Returns:
    The thread object representing the calling thread. The result of deleting this object is undefined.

  static Thread[] getAll();
    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.

  static int opApply(scope int delegate(ref Thread) dg);
    Operates on all threads currently being tracked by the system. The result of deleting any Thread object is undefined.

    Parameters:

    int delegate(ref Thread) dg | The supplied code as a delegate.

    Returns:
    Zero if all elemented are visited, nonzero if not.

  deprecated alias findThread;

void thread_init();
  Initializes the thread module. This function must be called by the garbage collector on startup and before any other thread routines are called.

bool thread_isMainThread();

Thread thread_attachThis();
Thread thread_attachByAddr(Thread.ThreadAddr addr);
Thread thread_attachByAddrB(Thread.ThreadAddr addr, void* bstack);
  Registers the calling thread for use with the D Runtime. If this routine is called for a thread which is already registered, the result is undefined.

deprecated nothrow void thread_setNeedLock(bool need);
  This should be handled automatically by thread_attach.

deprecated alias thread_attach;
deprecated alias thread_detach;
  Renamed to be more consistent with other extern (C) routines.

void thread_detachThis();
void thread_detachByAddr(Thread.ThreadAddr addr);
  Deregisters the calling thread from use with the runtime. If this routine is called for a thread which is already registered, the result is undefined.

static Thread thread_findByAddr(Thread.ThreadAddr addr);
  Search the list of all threads for a thread with the given thread identifier.

  Parameters:

  Thread.ThreadAddr addr | The thread identifier to search for.

  Returns:
  The thread object associated with the thread identifier, null if not found.

void thread_joinAll();
  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.

nothrow bool thread_needLock();
  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();
  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();
  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);
  The main entry point for garbage collection. The supplied delegate will be passed ranges representing both stack and register values.

  Parameters:

  scanAllThreadsFn scan | The scanner function. It should scan from p1 through p2 - 1.
  void* curStackTop | An optional pointer to the top of the calling thread's stack.

  In:
  This routine must be preceded by a call to thread_suspendAll.

class ThreadGroup;
  This class is intended to simplify certain common programming techniques.

  final Thread create(void function() fn);
    Creates and starts a new Thread object that executes fn and adds it to the list of tracked threads.

    Parameters:

    void function() fn | The thread function.

    Returns:
    A reference to the newly created thread.

  final Thread create(void delegate() dg);
    Creates and starts a new Thread object that executes dg and adds it to the list of tracked threads.

    Parameters:

    void delegate() dg | The thread function.

    Returns:
    A reference to the newly created thread.

  final void add(Thread t);
    Add t to the list of tracked threads if it is not already being tracked.

    Parameters:

    Thread t | The thread to add.

    In:
    t must not be null.

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

    Parameters:

    Thread t | The thread to remove.

    In:
    t must not be null.

  final int opApply(scope int delegate(ref Thread) dg);
    Operates on all threads currently tracked by this object.

  final void joinAll(bool rethrow = true);
    Iteratively joins all tracked threads. This function will block add, remove, and opApply until it completes.

    Parameters:

    bool rethrow | Rethrow 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:

       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.

    Parameters:

    void function() fn | The thread function.
    size_t sz | The stack size for this fiber.

    In:
    fn must not be null.

  this(void delegate() dg, size_t sz = PAGESIZE);
    Initializes a fiber object which is associated with a dynamic D function.

    Parameters:

    void delegate() dg | The thread function.
    size_t sz | The stack size for this fiber.

    In:
    dg must not be null.

  final Object call(bool rethrow = true);
    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.

    Parameters:

    bool rethrow | Rethrow 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.

  final void reset();
    Resets this fiber so that it may be re-used. 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.

  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

  final const State state();
    Gets the current state of this fiber.

    Returns:
    The state of this fiber as an enumerated value.

  static void yield();
    Forces a context switch to occur away from the calling fiber.

  static void yieldAndThrow(Throwable t);
    Forces a context switch to occur away from the calling fiber and then throws obj in the calling fiber.

    Parameters:

    Throwable t | The object to throw.

    In:
    t must not be null.

  static Fiber getThis();
    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.

Copyright Sean Kelly 2005 - 2009. | Page generated by Ddoc.