I would like to create a Rust semaphore wrapping the libc sem_post and sem_wait functions, both of which take a mutable int * parameter. This requires that the waiter and poster simultaneously have a mutable pointer to the same int. How can I arrange this without risking UB?
One thought I had was to use UnsafeCell:
use libc; use std::cell::UnsafeCell; pub struct Sema { sema: UnsafeCell<i32>, } impl Sema { pub fn post(&self) { unsafe { libc::sem_post(self.sema.get()) }; } pub fn wait(&self) { unsafe { libc::sem_wait(self.sema.get()) }; } } Is this safe, and is there a better way? Thanks for any help!
UnsafeCell<libc::sem_t>, otherwise your code is unsound on 64-bit systems.