rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.9k stars 111 forks source link

Separate APIs for spinning and non-spinning lazy statics #141

Open briansmith opened 5 years ago

briansmith commented 5 years ago

In my crate, ring I have use cases where I want to lazily initialize a value using only a spin lock (waiting for CPUID to finish) and where I want to lazily initialize a value using only libstd's synchronization primitives and never spin (opening a file lazily, where the file handle will be shared across threads). Currently this is impossible to do because the spin_no_std feature is all-or-none.

I propose that lazy_static! be augmented with two new macros lazy_static_spin! and lazy_static_std! which, respectively, use spin or libstd. Then the existing spin_no_std feature would simply control which of those two macros lazy_static! is implemented in terms of.

KodrAus commented 5 years ago

Hi @briansmith :wave:

Hmm, I think there's value in lazy_static remaining opaque with respect to the mechanism it uses for synchronization. If you need fine control over that then maybe you'd be best off building your own wrappers over std::sync::Once or spin::Once as needed? lazy_static itself is really just a thin (and continually thinning) shim over these APIs.

kami881 commented 5 years ago

Ndst1

matklad commented 4 years ago

@briansmith you might find this crate useful: https://docs.rs/conquer-once/0.1.2/conquer_once/