3 ms·
> (for example, Rust doesn't allow global mutable state as it wouldn't be able to prevent races accessing it from multiple threads). This is incorrect: in Rust
by LegionMammal978 4y ago
> (for example, Rust doesn't allow global mutable state as it wouldn't be able to prevent races accessing it from multiple threads).
This is incorrect: in Rust, you can declare global mutable variables, but it is unsafe to access them, since you must manually ensure there are no data races. You can also have global mutable state in safe code, as long as you protect it behind a Mutex or RwLock (which enforce exclusive mutability), or declare it as an atomic integer if it is small enough (since atomic ops do not cause data races).
- medo-bear 4y agocool but the article is not about rust. the author used a simple example without elaborating on the details
- iudqnolq 4y agoRead in context it's a pretty reasonable offhand example. > Avoiding global variables is usually considered good practise, and some systems ban them for other reasons anyway (for example, Rust doesn't allow global mutable state as it wouldn't be able to prevent races accessing it from multiple threads). Rust does avoid global variables. You will very very rarely see a global mutex in a Rust library, and only occasionally see it in an application. (The most recent time I saw a Rust mutex was to implement string interning in wasm, a platform without atomics. So it's basically free).
- LegionMammal978 4y ago> Rust does avoid global variables. You will very very rarely see a global mutex in a Rust library, and only occasionally see it in an application. (The most recent time I saw a Rust mutex was to implement string interning in wasm, a platform without atomics. So it's basically free). Sure, global mutexes are pretty uncommon. (Although I can spy some in a few of the largest crates, such as log, crossbeam-utils, thread_local, rayon-core, and openssl.) But it's far from uncommon to use global atomic variables. Atomic counters are often used for unique ID generators, e.g., in autocfg, url, tokio, futures-util, uuid, same-file, and gimli. Atomics are also used as mutexes for external data, e.g., in parking_lot and backtrace, as well as direct storage of mutable flags and other data, e.g., in proc-macro2, time, parking_lot_core, tracing-core, and crossbeam-epoch. I just don't want people getting the impression that Rust is among the "systems [that] ban [global variables]". I don't deny that it discourages global mutable state for most situations, but its overall approach is far more pragmatic than a simple ban.