Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Fix thread count timing
  • Loading branch information
youknowone committed Jan 18, 2026
commit 673b38b4c789aa0228e9ebe91e7071dd5b05d43e
28 changes: 15 additions & 13 deletions crates/vm/src/stdlib/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,14 +421,14 @@ pub(crate) mod _thread {
vm.new_thread()
.make_spawn_func(move |vm| run_thread(func, args, vm)),
)
.map(|handle| {
vm.state.thread_count.fetch_add(1);
thread_to_id(&handle)
})
.map(|handle| thread_to_id(&handle))
.map_err(|err| vm.new_runtime_error(format!("can't start new thread: {err}")))
}

fn run_thread(func: ArgCallable, args: FuncArgs, vm: &VirtualMachine) {
// Increment thread count when thread actually starts executing
vm.state.thread_count.fetch_add(1);

match func.invoke(args, vm) {
Ok(_obj) => {}
Err(e) if e.fast_isinstance(vm.ctx.exceptions.system_exit) => {}
Expand Down Expand Up @@ -1168,13 +1168,6 @@ pub(crate) mod _thread {
// Mark as done
inner_for_cleanup.lock().state = ThreadHandleState::Done;

// Signal waiting threads that this thread is done
{
let (lock, cvar) = &*done_event_for_cleanup;
*lock.lock() = true;
cvar.notify_all();
}

// Handle sentinels
for lock in SENTINELS.take() {
if lock.mu.is_locked() {
Expand All @@ -1189,8 +1182,19 @@ pub(crate) mod _thread {
crate::vm::thread::cleanup_current_thread_frames(vm);

vm_state.thread_count.fetch_sub(1);

// Signal waiting threads that this thread is done
// This must be LAST to ensure all cleanup is complete before join() returns
{
let (lock, cvar) = &*done_event_for_cleanup;
*lock.lock() = true;
cvar.notify_all();
}
}

// Increment thread count when thread actually starts executing
vm_state.thread_count.fetch_add(1);

// Run the function
match func.invoke((), vm) {
Ok(_) => {}
Expand All @@ -1206,8 +1210,6 @@ pub(crate) mod _thread {
}))
.map_err(|err| vm.new_runtime_error(format!("can't start new thread: {err}")))?;

vm.state.thread_count.fetch_add(1);

// Store the join handle
handle.inner.lock().join_handle = Some(join_handle);

Expand Down
Loading