From b862534be5066f28ea0a21ddcb666ff392f2ed44 Mon Sep 17 00:00:00 2001 From: Philipp Oppermann Date: Wed, 1 Apr 2020 12:53:25 +0200 Subject: [PATCH] Use a static counter for assigning task IDs (#782) Deriving the task ID from the heap address of the future does not work for zero-sized futures because they are not backed by a real allocation. --- src/task/executor.rs | 2 +- src/task/mod.rs | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/task/executor.rs b/src/task/executor.rs index 51aa8636..55410ceb 100644 --- a/src/task/executor.rs +++ b/src/task/executor.rs @@ -38,7 +38,7 @@ impl Executor { fn run_ready_tasks(&mut self) { while let Some(mut task) = self.task_queue.pop_front() { - let task_id = task.id(); + let task_id = task.id; if !self.waker_cache.contains_key(&task_id) { self.waker_cache.insert(task_id, self.create_waker(task_id)); } diff --git a/src/task/mod.rs b/src/task/mod.rs index a69650a3..4a1480e3 100644 --- a/src/task/mod.rs +++ b/src/task/mod.rs @@ -2,6 +2,7 @@ use alloc::boxed::Box; use core::{ future::Future, pin::Pin, + sync::atomic::{AtomicU64, Ordering}, task::{Context, Poll}, }; @@ -10,12 +11,14 @@ pub mod keyboard; pub mod simple_executor; pub struct Task { + id: TaskId, future: Pin>>, } impl Task { pub fn new(future: impl Future + 'static) -> Task { Task { + id: TaskId::new(), future: Box::pin(future), } } @@ -23,14 +26,14 @@ impl Task { fn poll(&mut self, context: &mut Context) -> Poll<()> { self.future.as_mut().poll(context) } - - fn id(&self) -> TaskId { - use core::ops::Deref; - - let addr = Pin::deref(&self.future) as *const _ as *const () as usize; - TaskId(addr) - } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -struct TaskId(usize); +struct TaskId(u64); + +impl TaskId { + fn new() -> Self { + static NEXT_ID: AtomicU64 = AtomicU64::new(0); + TaskId(NEXT_ID.fetch_add(1, Ordering::Relaxed)) + } +}