top | item 41929215

(no title)

willglynn | 1 year ago

> In Rust, the main thread is special. (I consider this unfortunate, but web people like it, because inside browsers, the main thread is very special.) If the main thread exits, all the other threads are silently killed.

Rust inherits this from `pthread_detach()`:

       The detached attribute merely determines the behavior of the
       system when the thread terminates; it does not prevent the thread
       from being terminated if the process terminates using exit(3) (or
       equivalently, if the main thread returns).

discuss

order

wahern|1 year ago

The main thread is special because that's how the runtime works on Unix. In particular, when "main" exits, the process exits. This is required by the C standard. It's also fundamentally built into how Unix processes work, as certain global variables, like argv and environ strings, typically are stored on the main thread's stack, so if the main thread is destroyed those references become invalid.

In principle Rust could have defined its environment to not make the main thread special, but then it would need some additional runtime magic on Unix systems, including having the main thread poll for all other threads to exit, which in turn would require it to add a layer of indirection to the system's threading runtime (e.g. wrapping pthreads) to be able to track all threads.

kelnos|1 year ago

> In principle Rust could have defined its environment to not make the main thread special...

Not to mention they'd have to be very careful with what they do on the main thread after they start up the application's first thread (e.g. allocating memory via malloc() is out), since there are quite a few things that are not safe to do (like fork() that's not immediately followed by exec()) in a multi-threaded program. So even a "single-threaded" Rust program would become multi-threaded, and assume all those problems.