Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Forums
  - IRC
  - Wiki
  - GitHub
  - Issues
  - Foundation
  - Donate
- Resources
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

# core.thread

The `thread` module provides support for `thread` creation and management.
License:
Distributed under the Boost Software License 1.0. (See accompanying file LICENSE)
Authors:
Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak

Source: core/thread.d

alias `getpid` = core.sys.posix.unistd.`getpid`;
  Returns the process ID of the calling process, which is guaranteed to be unique on the system. This call is always successful.

  Example:

      writefln("Current process id: %s", getpid());

class `ThreadException`: object.Exception;
  Base class for thread exceptions.
class `ThreadError`: object.Error;
  Base class for thread errors to be used for function inside GC when allocations are unavailable.
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.
  Examples:

      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();

  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 nothrow Thread `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 @property ThreadID `id`();
    Gets the OS identifier for this thread.
    Returns:
    If the thread hasn't been started yet, returns ThreadID.init. Otherwise, returns the result of GetCurrentThreadId on Windows, and pthread_self on POSIX.
    The value is unique for the current process.
  final @property string `name`();
    Gets the user-readable label for this thread.
    Returns:
    The `name` of this thread.
  final @property void `name`(string `val`);
    Sets the user-readable label for this thread.
    Parameters:

    string `val` | The new `name` of this thread.

  final @property 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 @property 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 nothrow @property 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 maximum valid priority for the scheduling policy of the process.
  const int `PRIORITY_DEFAULT`;
    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.
  final @property int `priority`();
    Gets the scheduling `priority` for the associated thread.

    Note: Getting the `priority` of a thread that already terminated might return the default `priority`.

    Returns:
    The scheduling `priority` of this thread.
  final @property void `priority`(int `val`);
    Sets the scheduling `priority` for the associated thread.

    Note: Setting the `priority` of a thread that already terminated might have no effect.

    Parameters:

    int `val` | The new scheduling `priority` of this thread.

  static nothrow @nogc void `sleep`(Duration `val`);
    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:

    Duration `val` | The minimum duration the calling thread should be suspended.

    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

  static nothrow @nogc void `yield`();
    Forces a context switch to occur away from the calling thread.
  static nothrow 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. If the current thread is not attached to the runtime, a `null` reference is returned.
  static Thread[] `getAll`();
    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).
    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. Note that threads passed to the callback might no longer run (see Thread.isRunning).
    Parameters:

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

    Returns:
    Zero if all elemented are visited, nonzero if not.
void `thread_setGCSignals`(int `suspendSignalNo`, int `resumeSignalNo`);
  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.
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.
void `thread_term`();
  Terminates the thread module. No other thread routine may be called afterwards.
bool `thread_isMainThread`();
Thread `thread_attachThis`();
  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.

  NOTE: This routine does not run thread-local static constructors when called. If full functionality as a D thread is desired, the following function must be called after `thread_attachThis`:

  extern (C) void rt_moduleTlsCtor();
nothrow void `thread_detachThis`();
  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.

  NOTE: This routine does not run thread-local static destructors when called. If full functionality as a D thread is desired, the following function must be called after `thread_detachThis`, particularly if the thread is being detached at some indeterminate time before program termination:

  extern(C) void rt_moduleTlsDtor();
void `thread_detachByAddr`(ThreadID `addr`);
void `thread_detachInstance`(Thread `t`);
  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.

  NOTE: This routine does not run thread-local static destructors when called. If full functionality as a D thread is desired, the following function must be called by the detached thread, particularly if the thread is being detached at some indeterminate time before program termination:

  extern(C) void rt_moduleTlsDtor();
static Thread `thread_findByAddr`(ThreadID `addr`);
  Search the list of all threads for a thread with the given thread identifier.
  Parameters:

  ThreadID `addr` | The thread identifier to search for.

  Returns:
  The thread object associated with the thread identifier, `null` if not found.
void `thread_setThis`(Thread `t`);
  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.
  Parameters:

  Thread `t` | A reference to the current thread. May be `null`.

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 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:
  ThreadError if the suspend operation fails for a running thread.
nothrow 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:
  ThreadError if the resume operation fails for a running thread.
enum `ScanType`: int;
  Indicates the kind of scan being performed by thread_scanAllType.
  `stack`
    The `stack` and/or registers are being scanned.
  `tls`
    TLS data is being scanned.
alias `ScanAllThreadsFn` = void delegate(void*, void*) nothrow;
alias `ScanAllThreadsTypeFn` = void delegate(ScanType, void*, void*) nothrow;
  The scanning function.
nothrow void `thread_scanAllType`(scope ScanAllThreadsTypeFn `scan`);
  The main entry point for garbage collection. The supplied delegate will be passed ranges representing both stack and register values.
  Parameters:

  ScanAllThreadsTypeFn `scan` | The scanner function. It should `scan` from p1 through p2 - 1.

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

nothrow void `thread_scanAll`(scope ScanAllThreadsFn `scan`);
  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.

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

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

  In: The calling thread must be attached to the runtime.

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

  In: The calling thread must be attached to the runtime.

bool `thread_inCriticalRegion`();
  Returns `true` if the current thread is in a critical region; otherwise, `false`.

  In: The calling thread must be attached to the runtime.

enum `IsMarked`: int;
  Indicates whether an address has been marked by the GC.
  `no`
    Address is not marked.
  `yes`
    Address is marked.
  `unknown`
    Address is not managed by the GC.
alias `IsMarkedDg` = int delegate(void* addr) nothrow;
  The isMarked callback function.
nothrow void `thread_processGCMarks`(scope IsMarkedDg `isMarked`);
  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.
  Parameters:

  IsMarkedDg `isMarked` | The function used to check if addr is marked.

  In: This routine must be called just prior to resuming all threads.

nothrow void* `thread_stackTop`();
  Returns the stack top of the currently active stack within the calling thread.

  In: The calling thread must be attached to the runtime.

  Returns:
  The address of the stack top.
nothrow void* `thread_stackBottom`();
  Returns the stack bottom of the currently active stack within the calling thread.

  In: The calling thread must be attached to the runtime.

  Returns:
  The address of the stack bottom.
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.

  Warning: Status registers are not saved by the current implementations. This means floating point exception status bits (overflow, divide by 0), rounding mode and similar stuff is set per-thread, not per `Fiber`!

  Warning: On ARM FPU registers are not saved if druntime was compiled as ARM_SoftFloat. If such a build is used on a ARM_SoftFP system which actually has got a FPU and other libraries are using the FPU registers (other code is compiled as ARM_SoftFP) this can cause problems. Druntime must be compiled as ARM_SoftFP in this case.

  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.
  nothrow this(void function() `fn`, size_t `sz` = PAGESIZE * 4);
    Initializes a fiber object which is associated with a static D function.
    Parameters:

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

    In: `fn` must not be `null`.

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

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

    In: `dg` must not be `null`.

  final Throwable `call`(Rethrow `rethrow` = Rethrow.yes);
  final Throwable `call`(Rethrow rethrow)();
  deprecated final Throwable `call`(bool `rethrow`);
    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:

    Rethrow `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.
  enum `Rethrow`: bool;
    Flag to control rethrow behavior of call
  final nothrow void `reset`();
  final nothrow void `reset`(void function() `fn`);
  final nothrow void `reset`(void delegate() `dg`);
    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.

    In: This fiber must be in state TERM or HOLD.

  enum `State`: int;
    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 nothrow @property State `state`();
    Gets the current `state` of this fiber.
    Returns:
    The `state` of this fiber as an enumerated value.
  static nothrow void `yield`();
    Forces a context switch to occur away from the calling fiber.
  static nothrow 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 nothrow 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 within this thread. The result of deleting this object is undefined.
alias `ThreadID` = uint;
  Represents the ID of a thread, as returned by Thread.id. The exact type varies from platform to platform.

Copyright Sean Kelly 2005 - 2012. | Page generated by Ddoc on Thu Mar 9 17:49:39 2017