2 ms·
Static initialization? Does that mean initializing the mutex before main?
by ReactiveJelly 5y ago
Static initialization?
Does that mean initializing the mutex before main?
- nyanpasu64 5y agoThere are two types of static initialization (initialization before main): constant and running code. Only C++ supports running code before main to initialize static-lifetime variables, and this feature is regarded as dangerous due to the static initialization order fiasco (referencing non-constant-initialized globals defined in other TUs will randomly see either all zeros or the initialized value, depending on the linking order of TUs). (C on Unix has a platform-specific __attribute__ ((constructor)) to do the same thing, but it's not standardized). Standard C and Rust don't allow running code before main to statically initialize mutexes. Rust mutexes cannot be statically const-initialized either. So if you want a global mutex, you have to use a once_cell::sync::Lazy or lazy_static! to construct the contents on first read (adding an extra branch on every access). On the other hand, parking_lot offers a statically constructible (const-initializable) Mutex independent of OS synchronization primitives (https://docs.rs/parking_lot/latest/parking_lot/type.Mutex.html https://docs.rs/parking_lot/latest/parking_lot/type.Mutex.ht...) which doesn't require a OnceCell/Lazy/lazy_static around it.