Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow non-RAII semaphore usage, fix semaphore guard lifetime issue #46

Merged
merged 2 commits into from
Jan 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions freertos-rust/src/semaphore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,23 @@ impl Semaphore {

/// Lock this semaphore in a RAII fashion
pub fn lock<D: DurationTicks>(&self, max_wait: D) -> Result<SemaphoreGuard, FreeRtosError> {
self.take(max_wait).map(|()| SemaphoreGuard { owner: self })
}

/// Returns `true` on success, `false` when semaphore count already reached its limit
pub fn give(&self) -> bool {
unsafe { freertos_rs_give_mutex(self.semaphore) == 0 }
}

pub fn take<D: DurationTicks>(&self, max_wait: D) -> Result<(), FreeRtosError> {
unsafe {
let res = freertos_rs_take_mutex(self.semaphore, max_wait.to_ticks());

if res != 0 {
return Err(FreeRtosError::Timeout);
}

Ok(SemaphoreGuard {
__semaphore: self.semaphore,
})
Ok(())
}
}
}
Expand All @@ -63,14 +70,12 @@ impl Drop for Semaphore {
}

/// Holds the lock to the semaphore until we are dropped
pub struct SemaphoreGuard {
__semaphore: FreeRtosSemaphoreHandle,
pub struct SemaphoreGuard<'a> {
owner: &'a Semaphore,
}

impl Drop for SemaphoreGuard {
impl<'a> Drop for SemaphoreGuard<'a> {
fn drop(&mut self) {
unsafe {
freertos_rs_give_mutex(self.__semaphore);
}
self.owner.give();
}
}