pub struct SharedMutex { /* private fields */ }
Expand description
Simple mutex that can be shared between processes.
This mutex is NOT recursive, so it will deadlock on relock.
Dropping mutex in creating process while mutex being locked or waited will cause undefined behaviour. It is recommended to drop this mutex in creating process only after no other process has access to it.
For more information see pthread_mutex_init
, pthread_mutex_lock
and SharedMemoryObject
.
§Example
let mut mutex = SharedMutex::new()?;
let pid = unsafe { fork() };
assert!(pid >= 0);
if pid == 0 {
println!("child lock()");
mutex.lock()?;
println!("child locked");
sleep(Duration::from_millis(40));
println!("child unlock()");
mutex.unlock()?;
} else {
sleep(Duration::from_millis(20));
println!("parent lock()");
mutex.lock()?;
println!("parent locked");
sleep(Duration::from_millis(20));
println!("parent unlock()");
mutex.unlock()?;
}
Output:
child lock()
child locked
parent lock()
child unlock()
parent locked
parent unlock()
Implementations§
Sourcepub fn new() -> Result<Self>
pub fn new() -> Result<Self>
Creates new SharedMutex
§Errors
If allocation or initialization fails returns error from last_os_error
.
Sourcepub fn lock(&mut self) -> Result<()>
pub fn lock(&mut self) -> Result<()>
Locks mutex.
This function will block until mutex is locked.
§Errors
If any pthread call fails, returns error from last_os_error
. For possible errors see pthread_mutex_lock
.
Sourcepub fn unlock(&mut self) -> Result<()>
pub fn unlock(&mut self) -> Result<()>
Unlocks mutex.
This function must be called from the same process that called lock
previously.
§Errors
If any pthread call fails, returns error from last_os_error
. For possible errors see pthread_mutex_unlock
.