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.
This commit is contained in:
Philipp Oppermann
2020-04-01 12:53:25 +02:00
committed by GitHub
parent e465c5b278
commit b862534be5
2 changed files with 12 additions and 9 deletions

View File

@@ -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));
}

View File

@@ -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<Box<dyn Future<Output = ()>>>,
}
impl Task {
pub fn new(future: impl Future<Output = ()> + '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))
}
}