pub struct Mutex<T> { /* private fields */ }
Expand description
A mutual exclusion primitive useful for protecting shared data.
This mutex will block the execution waiting for the lock to become
available. The mutex can be created via a new
constructor.
Each mutex has a type parameter which represents the data that it is
protecting. The data can only be accessed through the RAII guard
MutexGuard
returned from lock
,
which guarantees that data access only occurs when the mutex is
locked.
§Examples
This example (program A), after locking the mutex, sends the PING
message
to another program (program B) and waits for a reply. If any other program
(program C) tries to invoke program A, it will wait until program A receives
the PONG
reply from program B and unlocks the mutex.
use gstd::{msg, sync::Mutex, ActorId};
static mut DEST: ActorId = ActorId::zero();
static MUTEX: Mutex<()> = Mutex::new(());
#[no_mangle]
extern "C" fn init() {
// `some_address` can be obtained from the init payload
# let some_address = ActorId::zero();
unsafe { DEST = some_address };
}
#[gstd::async_main]
async fn main() {
let payload = msg::load_bytes().expect("Unable to load payload bytes");
if payload == b"START" {
let _unused = MUTEX.lock().await;
let reply = msg::send_bytes_for_reply(unsafe { DEST }, b"PING", 0, 0)
.expect("Unable to send bytes")
.await
.expect("Error in async message processing");
if reply == b"PONG" {
msg::reply(b"SUCCESS", 0).unwrap();
} else {
msg::reply(b"FAIL", 0).unwrap();
}
}
}
# fn main() {}
Implementations§
source§impl<T> Mutex<T>
impl<T> Mutex<T>
sourcepub fn lock(&self) -> MutexLockFuture<'_, T> ⓘ
pub fn lock(&self) -> MutexLockFuture<'_, T> ⓘ
Acquire a mutex, protecting the subsequent code from execution by other actors until the mutex hasn’t been unlocked.
This function will block access to the section of code by other programs or users that invoke the same program. If another actor reaches the code blocked by the mutex, it goes to the wait state until the mutex unlocks. RAII guard wrapped in the future is returned to allow scoped unlock of the lock. When the guard goes out of scope, the mutex will be unlocked.