use intrusive_collections::linked_list::LinkOps;
use intrusive_collections::{Adapter, DefaultPointerOps, LinkedList, LinkedListLink, UnsafeRef};
use pi_async_task::definitions::{CancelRequestStatus, FutureDropStatus, RunOutcome, TerminationKind};
use pi_async_task::{create, create_local, QueueEntry, Runnable, Schedule, TaskOptions, TaskThread};
use std::future::{ready, Future};
use std::ptr::NonNull;
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::Arc;
use std::task::{Context, Poll, Waker};
struct EntryAdapter {
links: LinkOps,
pointers: DefaultPointerOps<UnsafeRef<QueueEntry>>,
}
unsafe impl Adapter for EntryAdapter {
type LinkOps = LinkOps;
type PointerOps = DefaultPointerOps<UnsafeRef<QueueEntry>>;
unsafe fn get_value(&self, link: NonNull<LinkedListLink>) -> *const QueueEntry {
unsafe { QueueEntry::node_from_link(link) }.as_ptr()
}
unsafe fn get_link(&self, value: *const QueueEntry) -> NonNull<LinkedListLink> {
let node = NonNull::new(value.cast_mut()).expect("链节点地址有效");
unsafe { QueueEntry::link_from_node(node) }
}
fn link_ops(&self) -> &Self::LinkOps {
&self.links
}
fn link_ops_mut(&mut self) -> &mut Self::LinkOps {
&mut self.links
}
fn pointer_ops(&self) -> &Self::PointerOps {
&self.pointers
}
}
struct Entries<'owner> {
owner: &'owner TaskThread,
entries: LinkedList<EntryAdapter>,
}
impl<'owner> Entries<'owner> {
fn new(owner: &'owner TaskThread) -> Self {
let adapter = EntryAdapter { links: LinkOps, pointers: DefaultPointerOps::new() };
Self { owner, entries: LinkedList::new(adapter) }
}
fn push_back(&mut self, task: Runnable) -> NonNull<QueueEntry> {
let node = unsafe { QueueEntry::store_with_unbound(task, self.owner.id()) }
.unwrap_or_else(|_| panic!("合法原值应能存入"));
self.entries.push_back(unsafe { UnsafeRef::from_raw(node.as_ptr()) });
node
}
fn pop_front(&mut self) -> Option<Runnable> {
let node = self.entries.pop_front()?;
Some(unsafe { QueueEntry::take_with_unbound(NonNull::from(&*node), self.owner.id()) })
}
}
impl Drop for Entries<'_> {
fn drop(&mut self) {
while let Some(task) = self.pop_front() {
drop(task);
}
}
}
#[derive(Clone, Default)]
struct ScheduleCalls(Arc<AtomicUsize>);
impl Schedule for ScheduleCalls {
fn schedule(&self, task: Runnable) {
self.0.fetch_add(1, SeqCst);
drop(task);
}
}
struct DropCount(Arc<AtomicUsize>);
impl Drop for DropCount {
fn drop(&mut self) {
self.0.fetch_add(1, SeqCst);
}
}
#[test]
fn test_mixed_entries_preserve_order_and_original_state() {
let owner = TaskThread::new();
let schedule = ScheduleCalls::default();
let polls = Arc::new(AtomicUsize::new(0));
let drops = Arc::new(AtomicUsize::new(0));
let original = create(
{
let polls = Arc::clone(&polls);
let drop_count = DropCount(Arc::clone(&drops));
async move {
let _keep = &drop_count;
polls.fetch_add(1, SeqCst);
}
},
schedule.clone(),
(),
TaskOptions::intrusive_local_and_mpsc(),
)
.unwrap_or_else(|_| panic!("创建未绑定任务"));
let mut entries = Entries::new(&owner);
let original_id = original.runnable.id();
assert_eq!(original.runnable.snapshot().owner, None);
let first_node = entries.push_back(original.runnable);
let local = create_local(&owner, ready(73_u32), schedule.clone(), (), TaskOptions::intrusive())
.unwrap_or_else(|_| panic!("创建本地任务"));
let registration = local.runnable.admit(&owner).expect("接纳本地任务");
let local_snapshot = local.runnable.snapshot();
let local_join = local.join;
entries.push_back(local.runnable);
std::thread::spawn(move || {
let waker = original.control.waker();
waker.wake_by_ref();
waker.wake_by_ref();
original.control.cancel();
})
.join()
.expect("外线程完成控制请求");
assert_eq!(schedule.0.load(SeqCst), 0);
assert_eq!(drops.load(SeqCst), 0);
let original = entries.pop_front().expect("队首是未绑定任务");
assert_eq!(original.id(), original_id);
let snapshot = original.snapshot();
assert_eq!(snapshot.owner, None);
assert!(!snapshot.admitted);
assert_eq!(snapshot.cancellation, CancelRequestStatus::Recorded);
assert_eq!(entries.push_back(original), first_node);
let local = entries.pop_front().expect("接下来取回原本地任务");
assert_eq!(local.snapshot(), local_snapshot);
assert_eq!(
local.run(&owner).unwrap_or_else(|_| panic!("运行本地任务")),
RunOutcome::Finished(TerminationKind::Completed),
);
let mut local_join = std::pin::pin!(local_join);
assert!(matches!(
local_join.as_mut().poll(&mut Context::from_waker(Waker::noop())),
Poll::Ready(Ok(73)),
));
let original = entries.pop_front().expect("队尾是重新入链的原任务");
assert_eq!(original.snapshot(), snapshot);
assert_eq!(
original.run(&owner).unwrap_or_else(|_| panic!("清理原任务")),
RunOutcome::Finished(TerminationKind::Cancelled),
);
assert_eq!(polls.load(SeqCst), 0);
assert_eq!(drops.load(SeqCst), 1);
assert!(entries.pop_front().is_none());
assert_eq!(schedule.0.load(SeqCst), 0);
assert_eq!(owner.live_tasks(), 0);
drop(registration);
}
#[test]
fn test_remaining_entry_can_be_released_without_admission() {
let owner = TaskThread::new();
let drops = Arc::new(AtomicUsize::new(0));
let schedule = ScheduleCalls::default();
let original = create(
{
let drop_count = DropCount(Arc::clone(&drops));
async move {
let _keep = &drop_count;
std::future::pending::<()>().await;
}
},
schedule.clone(),
(),
TaskOptions::intrusive(),
)
.unwrap_or_else(|_| panic!("创建待清理任务"));
let mut entries = Entries::new(&owner);
let id = original.runnable.id();
entries.push_back(original.runnable);
assert_eq!(drops.load(SeqCst), 0);
let task = entries.pop_front().expect("退出时取回尚未运行的任务");
assert_eq!(task.id(), id);
drop(task);
let snapshot = original.control.snapshot();
assert_eq!(snapshot.owner, None);
assert!(!snapshot.admitted);
assert_eq!(snapshot.termination, Some(TerminationKind::Abandoned));
assert_eq!(snapshot.future_drop, FutureDropStatus::Confirmed);
assert!(entries.pop_front().is_none());
assert_eq!(schedule.0.load(SeqCst), 0);
assert_eq!(drops.load(SeqCst), 1);
}
#[test]
fn test_unlinked_entry_can_be_returned_and_reused() {
let owner = TaskThread::new();
let task = create(ready(()), ScheduleCalls::default(), (), TaskOptions::intrusive())
.unwrap_or_else(|_| panic!("创建未绑定任务"))
.runnable;
let before = task.snapshot();
let task = unsafe { QueueEntry::store(task, owner.id()) }.unwrap_err();
let mut address = None;
let mut task = task;
for _ in 0..2 {
let node = unsafe { QueueEntry::store_with_unbound(task, owner.id()) }
.unwrap_or_else(|_| panic!("存入未绑定任务"));
task = unsafe { QueueEntry::take_with_unbound(node, owner.id()) };
assert_eq!(task.snapshot(), before);
if let Some(previous) = address {
assert_eq!(node, previous);
}
address = Some(node);
}
assert_eq!(
task.run(&owner).unwrap_or_else(|_| panic!("运行原任务")),
RunOutcome::Finished(TerminationKind::Completed),
);
}
#[test]
fn test_entry_refuses_foreign_owner_and_missing_link() {
let owner = TaskThread::new();
let foreign = TaskThread::new();
let task = create_local(&foreign, ready(()), ScheduleCalls::default(), (), TaskOptions::intrusive())
.unwrap_or_else(|_| panic!("创建属于另一域的任务"))
.runnable;
let before = task.snapshot();
let task = unsafe { QueueEntry::store_with_unbound(task, owner.id()) }.unwrap_err();
assert_eq!(task.snapshot(), before);
assert_eq!(
task.run(&foreign).unwrap_or_else(|_| panic!("在原所属域运行")),
RunOutcome::Finished(TerminationKind::Completed),
);
for options in [TaskOptions::plain(), TaskOptions::intrusive_mpsc()] {
let task = create(ready(()), ScheduleCalls::default(), (), options)
.unwrap_or_else(|_| panic!("创建无本地链接的任务"))
.runnable;
let before = task.snapshot();
let task = unsafe { QueueEntry::store_with_unbound(task, owner.id()) }.unwrap_err();
assert_eq!(task.snapshot(), before);
assert_eq!(
task.run(&owner).unwrap_or_else(|_| panic!("运行无本地链接的原任务")),
RunOutcome::Finished(TerminationKind::Completed),
);
}
}