Skip to content

thread spawn is broken on wasm32-wasip1-threads for building library #146843

Description

@oligamiq

I tried this code:

fn main() {
    std::thread::spawn(|| {
        println!("Hello from a thread!");
    });
}

I expected to see this happen: success

Instead, this happened: infinity loop

Meta

rustc --version --verbose:

rustc 1.92.0-nightly (4645a7988 2025-09-17)
binary: rustc
commit-hash: 4645a7988177c286f61609cc667ecae4c571a2e8
commit-date: 2025-09-17
host: x86_64-pc-windows-msvc
release: 1.92.0-nightly
LLVM version: 21.1.1

This relates to rust-lang/rust#108097
When generating as a bin, if you attempt to perform a thread spawn before the generated _start function is called, the program falls into an infinite loop and halts. This issue occurs regardless of whether you use nightly or not.

Furthermore, when building as a lib, thread spawning does not work at all.
The reason is that in the case of bin, crt1-command.o is linked, and within the generated _start function, __wasi_init_tp is invoked, which initializes the thread-related state. However, in the case of lib, the expected crt1-reactor.o should be linked, but its _initialize function is not exported, so initialization never happens and threads fail to work correctly.

As a workaround, you can use the following:

unsafe extern "C" {
    // Initialize thread-local storage for WASI threads
    // In the current version of Rust,
    // thread initialization is not performed.
    // Therefore, we must force linking to perform initialization.
    // https://github.com/rust-lang/rust/pull/108097
    fn __wasi_init_tp();
    fn __wasm_call_ctors();
}

pub extern "C" fn _initialize() {
    unsafe { __wasi_init_tp() };
    unsafe { __wasm_call_ctors() };
}

As also noted in
#146721,
I honestly cannot understand why thread::spawn is so broken in this area.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-threadArea: `std::thread`C-bugCategory: This is a bug.O-wasiOperating system: Wasi, Webassembly System InterfaceO-wasip1-threadsOperating system: *-wasmp1-threads, WASI Preview1 with atomics and threadsO-wasmTarget: WASM (WebAssembly), http://webassembly.org/T-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions