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

Executor: Replace unnecessary atomics in runqueue #1361

Merged
merged 1 commit into from
Apr 15, 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
25 changes: 16 additions & 9 deletions embassy-executor/src/raw/run_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ use core::ptr::NonNull;
use atomic_polyfill::{AtomicPtr, Ordering};

use super::{TaskHeader, TaskRef};
use crate::raw::util::SyncUnsafeCell;

pub(crate) struct RunQueueItem {
next: AtomicPtr<TaskHeader>,
next: SyncUnsafeCell<Option<TaskRef>>,
}

impl RunQueueItem {
pub const fn new() -> Self {
Self {
next: AtomicPtr::new(ptr::null_mut()),
next: SyncUnsafeCell::new(None),
}
}
}
Expand Down Expand Up @@ -51,7 +52,12 @@ impl RunQueue {
self.head
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |prev| {
was_empty = prev.is_null();
task.header().run_queue_item.next.store(prev, Ordering::Relaxed);
unsafe {
// safety: the pointer is either null or valid
let prev = NonNull::new(prev).map(|ptr| TaskRef::from_ptr(ptr.as_ptr()));
// safety: there are no concurrent accesses to `next`
task.header().run_queue_item.next.set(prev);
}
Some(task.as_ptr() as *mut _)
})
.ok();
Expand All @@ -64,18 +70,19 @@ impl RunQueue {
/// and will be processed by the *next* call to `dequeue_all`, *not* the current one.
pub(crate) fn dequeue_all(&self, on_task: impl Fn(TaskRef)) {
// Atomically empty the queue.
let mut ptr = self.head.swap(ptr::null_mut(), Ordering::AcqRel);
let ptr = self.head.swap(ptr::null_mut(), Ordering::AcqRel);

// safety: the pointer is either null or valid
let mut next = unsafe { NonNull::new(ptr).map(|ptr| TaskRef::from_ptr(ptr.as_ptr())) };

// Iterate the linked list of tasks that were previously in the queue.
while let Some(task) = NonNull::new(ptr) {
let task = unsafe { TaskRef::from_ptr(task.as_ptr()) };
while let Some(task) = next {
// If the task re-enqueues itself, the `next` pointer will get overwritten.
// Therefore, first read the next pointer, and only then process the task.
let next = task.header().run_queue_item.next.load(Ordering::Relaxed);
// safety: there are no concurrent accesses to `next`
next = unsafe { task.header().run_queue_item.next.get() };

on_task(task);

ptr = next
}
}
}