1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
pub mod tasks_with_regular_pauses;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio::spawn;
use tokio::sync::Mutex;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::task::JoinHandle;
use tokio_interruptible_future::{InterruptError, interruptible_straight};
pub type TaskItem = Pin<Box<dyn Future<Output = ()> + Send>>;
pub struct TaskQueue
{
tx: Sender<TaskItem>,
pub(crate) rx: Arc<Mutex<Receiver<TaskItem>>>,
}
impl TaskQueue {
pub fn new() -> Self {
let (tx, rx) = channel(1);
Self {
tx,
rx: Arc::new(Mutex::new(rx)),
}
}
async fn _task(this: Arc<Mutex<Self>>) {
loop {
let this2 = this.clone();
let fut = {
let obj = this2.lock().await;
let rx = obj.rx.clone();
let mut rx = rx.lock().await;
rx.recv().await
};
if let Some(fut) = fut {
fut.await;
} else {
break;
}
}
}
pub fn spawn(
this: Arc<Mutex<Self>>,
notify_interrupt: async_channel::Receiver<()>,
) -> JoinHandle<Result<(), InterruptError>> {
spawn( interruptible_straight(notify_interrupt, async move {
Self::_task(this).await;
Ok(())
}))
}
pub async fn push_task(&self, fut: TaskItem) {
let _ = self.tx.send(fut).await;
}
}
pub struct ObjectSafeTaskQueue {
base: Arc<Mutex<TaskQueue>>,
}
impl ObjectSafeTaskQueue {
pub fn new() -> Self {
Self {
base: Arc::new(Mutex::new(TaskQueue::new())),
}
}
pub async fn get_arc(&self) -> &Arc<Mutex<TaskQueue>> {
&self.base
}
pub async fn get_arc_mut(&mut self) -> &Arc<Mutex<TaskQueue>> {
&mut self.base
}
pub async fn spawn(
&self,
notify_interrupt: async_channel::Receiver<()>,
) -> JoinHandle<Result<(), InterruptError>> {
TaskQueue::spawn(self.base.clone(), notify_interrupt)
}
pub async fn push_task(&self, fut: TaskItem) {
self.base.lock().await.push_task(fut).await
}
}