@@ -421,14 +421,14 @@ pub(crate) mod _thread {
421421 vm. new_thread ( )
422422 . make_spawn_func ( move |vm| run_thread ( func, args, vm) ) ,
423423 )
424- . map ( |handle| {
425- vm. state . thread_count . fetch_add ( 1 ) ;
426- thread_to_id ( & handle)
427- } )
424+ . map ( |handle| thread_to_id ( & handle) )
428425 . map_err ( |err| vm. new_runtime_error ( format ! ( "can't start new thread: {err}" ) ) )
429426 }
430427
431428 fn run_thread ( func : ArgCallable , args : FuncArgs , vm : & VirtualMachine ) {
429+ // Increment thread count when thread actually starts executing
430+ vm. state . thread_count . fetch_add ( 1 ) ;
431+
432432 match func. invoke ( args, vm) {
433433 Ok ( _obj) => { }
434434 Err ( e) if e. fast_isinstance ( vm. ctx . exceptions . system_exit ) => { }
@@ -1168,13 +1168,6 @@ pub(crate) mod _thread {
11681168 // Mark as done
11691169 inner_for_cleanup. lock( ) . state = ThreadHandleState :: Done ;
11701170
1171- // Signal waiting threads that this thread is done
1172- {
1173- let ( lock, cvar) = & * done_event_for_cleanup;
1174- * lock. lock( ) = true ;
1175- cvar. notify_all( ) ;
1176- }
1177-
11781171 // Handle sentinels
11791172 for lock in SENTINELS . take( ) {
11801173 if lock. mu. is_locked( ) {
@@ -1189,8 +1182,19 @@ pub(crate) mod _thread {
11891182 crate :: vm:: thread:: cleanup_current_thread_frames( vm) ;
11901183
11911184 vm_state. thread_count. fetch_sub( 1 ) ;
1185+
1186+ // Signal waiting threads that this thread is done
1187+ // This must be LAST to ensure all cleanup is complete before join() returns
1188+ {
1189+ let ( lock, cvar) = & * done_event_for_cleanup;
1190+ * lock. lock( ) = true ;
1191+ cvar. notify_all( ) ;
1192+ }
11921193 }
11931194
1195+ // Increment thread count when thread actually starts executing
1196+ vm_state. thread_count . fetch_add ( 1 ) ;
1197+
11941198 // Run the function
11951199 match func. invoke ( ( ) , vm) {
11961200 Ok ( _) => { }
@@ -1206,8 +1210,6 @@ pub(crate) mod _thread {
12061210 } ) )
12071211 . map_err ( |err| vm. new_runtime_error ( format ! ( "can't start new thread: {err}" ) ) ) ?;
12081212
1209- vm. state . thread_count . fetch_add ( 1 ) ;
1210-
12111213 // Store the join handle
12121214 handle. inner . lock ( ) . join_handle = Some ( join_handle) ;
12131215
0 commit comments