Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing access to FFI calls in Rust (via a global RWLock?)

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(());
like image 609
emk Avatar asked Nov 21 '14 16:11

emk


1 Answers

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.

like image 79
emk Avatar answered Oct 14 '22 07:10

emk