From 3937ff69ebbeeca3d228e6c80f87997e1120e288 Mon Sep 17 00:00:00 2001 From: Alexey Gerasev Date: Fri, 23 Dec 2022 19:27:59 +0700 Subject: [PATCH 1/2] Fix semaphore guard lifetime issue --- freertos-rust/src/semaphore.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/freertos-rust/src/semaphore.rs b/freertos-rust/src/semaphore.rs index afa9e16..ad989c8 100644 --- a/freertos-rust/src/semaphore.rs +++ b/freertos-rust/src/semaphore.rs @@ -47,9 +47,7 @@ impl Semaphore { return Err(FreeRtosError::Timeout); } - Ok(SemaphoreGuard { - __semaphore: self.semaphore, - }) + Ok(SemaphoreGuard { owner: self }) } } } @@ -63,14 +61,14 @@ 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); + freertos_rs_give_mutex(self.owner.semaphore); } } } From aded7941eb9ddae7b0a1e30c0c2f7dbe3409898d Mon Sep 17 00:00:00 2001 From: Alexey Gerasev Date: Fri, 23 Dec 2022 19:28:52 +0700 Subject: [PATCH 2/2] Allow non-RAII semaphore usage --- freertos-rust/src/semaphore.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/freertos-rust/src/semaphore.rs b/freertos-rust/src/semaphore.rs index ad989c8..1c98b8c 100644 --- a/freertos-rust/src/semaphore.rs +++ b/freertos-rust/src/semaphore.rs @@ -40,6 +40,15 @@ impl Semaphore { /// Lock this semaphore in a RAII fashion pub fn lock(&self, max_wait: D) -> Result { + 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(&self, max_wait: D) -> Result<(), FreeRtosError> { unsafe { let res = freertos_rs_take_mutex(self.semaphore, max_wait.to_ticks()); @@ -47,7 +56,7 @@ impl Semaphore { return Err(FreeRtosError::Timeout); } - Ok(SemaphoreGuard { owner: self }) + Ok(()) } } } @@ -67,8 +76,6 @@ pub struct SemaphoreGuard<'a> { impl<'a> Drop for SemaphoreGuard<'a> { fn drop(&mut self) { - unsafe { - freertos_rs_give_mutex(self.owner.semaphore); - } + self.owner.give(); } }