Skip to content

Commit

Permalink
Take critical section instead of unsafe
Browse files Browse the repository at this point in the history
  • Loading branch information
bugadani committed Dec 7, 2024
1 parent 13f324c commit 407b30a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 15 deletions.
10 changes: 5 additions & 5 deletions embassy-executor/src/raw/run_queue_critical_section.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use core::cell::Cell;

use critical_section::{CriticalSection, Mutex};
use critical_section::Mutex;

use super::TaskRef;

Expand Down Expand Up @@ -65,10 +65,10 @@ impl RunQueue {
// If the task re-enqueues itself, the `next` pointer will get overwritten.
// Therefore, first read the next pointer, and only then process the task.

// safety: we know if the task is enqueued, no one else will touch the `next` pointer.
let cs = unsafe { CriticalSection::new() };
next = task.header().run_queue_item.next.borrow(cs).get();
task.header().state.run_dequeue();
critical_section::with(|cs| {
next = task.header().run_queue_item.next.borrow(cs).get();
task.header().state.run_dequeue(cs);
});

on_task(task);
}
Expand Down
22 changes: 12 additions & 10 deletions embassy-executor/src/raw/state_critical_section.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use core::cell::Cell;

use critical_section::Mutex;
use critical_section::{CriticalSection, Mutex};

/// Task is claimed (it is being spawned)
pub(crate) const STATE_CLAIMED: u32 = 1 << 0;
Expand All @@ -24,13 +24,15 @@ impl State {
}

fn update<R>(&self, f: impl FnOnce(&mut u32) -> R) -> R {
critical_section::with(|cs| {
let s = self.state.borrow(cs);
let mut val = s.get();
let r = f(&mut val);
s.set(val);
r
})
critical_section::with(|cs| self.update_with_cs(cs, f))
}

fn update_with_cs<R>(&self, cs: CriticalSection<'_>, f: impl FnOnce(&mut u32) -> R) -> R {
let s = self.state.borrow(cs);
let mut val = s.get();
let r = f(&mut val);
s.set(val);
r
}

/// If task is idle, mark it as claimed and return true.
Expand Down Expand Up @@ -83,8 +85,8 @@ impl State {

/// Unmark the task as run-queued.
#[inline(always)]
pub fn run_dequeue(&self) {
self.update(|s| *s &= !STATE_RUN_QUEUED);
pub fn run_dequeue(&self, cs: CriticalSection<'_>) {
self.update_with_cs(cs, |s| *s &= !STATE_RUN_QUEUED);
}

/// Mark the task as timer-queued. Return whether it was newly queued (i.e. not queued before)
Expand Down

0 comments on commit 407b30a

Please sign in to comment.