-
Notifications
You must be signed in to change notification settings - Fork 13.8k
Description
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.