Skip to content

Commit

Permalink
Use a static counter for assigning task IDs
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
phil-opp committed Apr 1, 2020
1 parent e465c5b commit 8ef8bc9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/task/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down
17 changes: 10 additions & 7 deletions src/task/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use alloc::boxed::Box;
use core::{
future::Future,
pin::Pin,
sync::atomic::{AtomicU64, Ordering},
task::{Context, Poll},
};

Expand All @@ -10,27 +11,29 @@ pub mod keyboard;
pub mod simple_executor;

pub struct Task {
id: TaskId,
future: Pin<Box<dyn Future<Output = ()>>>,
}

impl Task {
pub fn new(future: impl Future<Output = ()> + 'static) -> Task {
Task {
id: TaskId::new(),
future: Box::pin(future),
}
}

fn poll(&mut self, context: &mut Context) -> Poll<()> {
self.future.as_mut().poll(context)
}
}

fn id(&self) -> TaskId {
use core::ops::Deref;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct TaskId(u64);

let addr = Pin::deref(&self.future) as *const _ as *const () as usize;
TaskId(addr)
impl TaskId {
fn new() -> Self {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
TaskId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct TaskId(usize);

0 comments on commit 8ef8bc9

Please sign in to comment.