Skip to content

Commit b862534

Browse files
authored
Use a static counter for assigning task IDs (phil-opp#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.
1 parent e465c5b commit b862534

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

src/task/executor.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ impl Executor {
3838

3939
fn run_ready_tasks(&mut self) {
4040
while let Some(mut task) = self.task_queue.pop_front() {
41-
let task_id = task.id();
41+
let task_id = task.id;
4242
if !self.waker_cache.contains_key(&task_id) {
4343
self.waker_cache.insert(task_id, self.create_waker(task_id));
4444
}

src/task/mod.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use alloc::boxed::Box;
22
use core::{
33
future::Future,
44
pin::Pin,
5+
sync::atomic::{AtomicU64, Ordering},
56
task::{Context, Poll},
67
};
78

@@ -10,27 +11,29 @@ pub mod keyboard;
1011
pub mod simple_executor;
1112

1213
pub struct Task {
14+
id: TaskId,
1315
future: Pin<Box<dyn Future<Output = ()>>>,
1416
}
1517

1618
impl Task {
1719
pub fn new(future: impl Future<Output = ()> + 'static) -> Task {
1820
Task {
21+
id: TaskId::new(),
1922
future: Box::pin(future),
2023
}
2124
}
2225

2326
fn poll(&mut self, context: &mut Context) -> Poll<()> {
2427
self.future.as_mut().poll(context)
2528
}
29+
}
2630

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

30-
let addr = Pin::deref(&self.future) as *const _ as *const () as usize;
31-
TaskId(addr)
34+
impl TaskId {
35+
fn new() -> Self {
36+
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
37+
TaskId(NEXT_ID.fetch_add(1, Ordering::Relaxed))
3238
}
3339
}
34-
35-
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
36-
struct TaskId(usize);

0 commit comments

Comments
 (0)