I'm trying to build a Rust wrapper for a C FFI library, but the underlying library has some functions which are not thread-safe. To access these functions, I need some kind of global lock which will protect the C library's state.
Is there any way to use a global std::sync::RWLock
or similar mechanism to control access to the C library?
Various obvious solutions fail because Rust does not allow non-trivial global initializers:
error: function calls in constants are limited to struct and enum constructors [E0015]
example.rs:18 static global_state_lock: RWLock<()> = RWLock::new(());
This problem can be solved using sync::mutex::StaticMutex
:
extern crate sync;
use sync::mutex::{StaticMutex, MUTEX_INIT};
static LIBRARY_LOCK: StaticMutex = MUTEX_INIT;
fn access_global_resource() {
let _ = LIBRARY_LOCK.lock();
unsafe { call_thread_unsafe_c_api(); }
}
Many thanks to arrrrrrr1 on #rust, who pointed me in the right direction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With