View source code Display the source code in std/concurrency.d from which this page was generated on github. 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 local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Function std.concurrency.spawn

Starts fn(args) in a new logical thread.

Executes the supplied function in a new logical thread represented by Tid. The calling thread is designated as the owner of the new thread. When the owner thread terminates an OwnerTerminated message will be sent to the new thread, causing an OwnerTerminated exception to be thrown on receive().

Prototype

Tid spawn(F, T...)(
  F fn,
  T args
)
if (isSpawnable!(F, T));

Parameters

NameDescription
fn The function to execute.
args Arguments to the function.

Returns

A Tid representing the new logical thread.

Notes

args must not have unshared aliasing. In other words, all arguments to fn must either be shared or immutable or have no pointer indirection. This is necessary for enforcing isolation among threads.

Example

import std.stdio, std.concurrency;

void f1(string str)
{
    writeln(str);
}

void f2(char[] str)
{
    writeln(str);
}

void main()
{
    auto str = "Hello, world";

    // Works:  string is immutable.
    auto tid1 = spawn(&f1, str);

    // Fails:  char[] has mutable aliasing.
    auto tid2 = spawn(&f2, str.dup);
}

Authors

Sean Kelly, Alex Rønne Petersen, Martin Nowak

License

Boost License 1.0.

Comments