Skip to content

single vs multi threaded as a builtin compile time option #1764

@andrewrk

Description

@andrewrk

There are many places where it matters whether code is single- or multi-threaded. For example:

  • whether to use a mutex to protect std.debug.warn
  • whether to use a mutex to protect panic
  • whether to call exit() or exit_group()
  • std.event.loop.initSingleThreaded() vs std.event.loop.initMultiThreaded()
  • whether coroutine await and coroutine return need to use atomic xchg operations to coordinate
  • whether to select a thread-safe allocator or non-thread-safe allocator by default

This proposal is to add --single-threaded as a build-option that is exposed as @import("builtin").single_threaded. Libraries can then use this to write code that is optimal for both cases. Most libraries can ignore the boolean; instead having functions that operate only on their input parameters or are simply not documented to be thread-safe. Where this value comes in useful is when a library has thread-safe functions, and the implementation can be optimized when it is known that there will only ever be a single thread. For example, std.atomic.Queue can simply omit all the mutex locking code, and its functions remain "thread safe" because there will only ever be one thread.

In the same way we plan to be able to set the build mode in a scope (#978) it should be possible to set the multithreaded-ness in a scope.

It's important to note that coroutines in particular, become extremely low overhead when compiling with --single-threaded. A --release-fast --single-threaded build which uses coroutines and always stack allocated the frames would in theory generate the exact same code as if it used normal functions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.proposalThis issue suggests language modifications. If it also has the "accepted" label then it is planned.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions