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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use std::{
    cell::RefCell,
    sync::{Arc, RwLock},
};

use async_task::Runnable;
use crossbeam_deque::{Injector, Steal, Stealer};
use futures_intrusive::sync::ManualResetEvent;
use futures_lite::{Future, FutureExt};
use once_cell::sync::Lazy;
use slab::Slab;

type NotifyChan = futures_intrusive::channel::Channel<(), [(); 256]>;

/// A self-contained executor context.
#[deprecated]
pub struct Executor {
    global_queue: Arc<Injector<Runnable>>,
    global_notifier: Arc<NotifyChan>,
    stealers: Arc<RwLock<Slab<Stealer<Runnable>>>>,
}

impl Default for Executor {
    fn default() -> Self {
        Self::new()
    }
}

impl Executor {
    /// Creates a new executor.
    pub fn new() -> Self {
        Self {
            global_queue: Arc::new(Injector::new()),
            global_notifier: futures_intrusive::channel::Channel::new().into(),
            stealers: Default::default(),
        }
    }

    /// Spawns a new task onto this executor.
    pub fn spawn<F>(&self, future: F) -> async_task::Task<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        let global_queue = self.global_queue.clone();
        let global_evt = self.global_notifier.clone();
        let (runnable, task) = async_task::spawn(future, move |runnable| {
            // attempt to spawn onto the worker that last ran
            let local_success: Result<(), Runnable> = TLS.with(|tls| {
                if let Ok(mut tls) = tls.try_borrow_mut() {
                    let tls = tls.as_mut();
                    if let Some(tls) = tls {
                        if !Arc::ptr_eq(&tls.global_queue, &global_queue) {
                            // shoot, does not belong to this executor
                            // log::trace!("oh no doesn't belong");
                            return Err(runnable);
                        } else {
                            log::trace!("scheduling locally");
                            unsafe { tls.schedule_local(runnable) }?;
                            return Ok(());
                        }
                    }
                }
                log::trace!("no TLS");
                Err(runnable)
            });
            if let Err(runnable) = local_success {
                // fall back to global queue
                log::trace!("scheduled globally");
                // let bt = Backtrace::new();
                // println!("{:?}", bt);
                global_queue.push(runnable);
                let _ = global_evt.try_send(());
            }
        });
        runnable.schedule();
        task
    }

    /// Obtains a new worker.
    pub fn worker(&self) -> Worker {
        let local_queue = crossbeam_deque::Worker::new_fifo();
        let stealer = local_queue.stealer();
        let notifier = Arc::new(ManualResetEvent::new(false));
        let worker_id = self.stealers.write().unwrap().insert(stealer);
        Worker {
            worker_id,
            local_queue,
            local_notifier: notifier,
            global_notifier: self.global_notifier.clone(),
            global_queue: self.global_queue.clone(),
            stealers: self.stealers.clone(),
        }
    }

    /// Rebalance the executor. Can/should be called from a monitor thread.
    pub fn rebalance(&self) {
        // all we need to do is to notify something.
        let _ = self.global_notifier.try_send(());
    }
}

thread_local! {
    static TLS: RefCell<Option<TlsState>> = Default::default();
}

struct TlsState {
    inner_sender: Vec<Runnable>,
    local_notifier: Arc<ManualResetEvent>,
    global_queue: Arc<Injector<Runnable>>, // for identification purposes
}

impl Drop for TlsState {
    fn drop(&mut self) {
        for runnable in self.inner_sender.drain(..) {
            self.global_queue.push(runnable);
        }
    }
}

impl TlsState {
    #[inline]
    unsafe fn schedule_local(&mut self, task: Runnable) -> Result<(), Runnable> {
        // *self.counter.get() += 1;
        // if *self.counter.get() % 256 == 0 {
        //     return Err(task);
        // }
        self.inner_sender.push(task);
        self.local_notifier.set();
        Ok(())
    }
}
#[deprecated]
pub struct Worker {
    worker_id: usize,

    local_queue: crossbeam_deque::Worker<Runnable>,
    local_notifier: Arc<ManualResetEvent>,
    global_notifier: Arc<NotifyChan>,
    global_queue: Arc<Injector<Runnable>>,
    stealers: Arc<RwLock<Slab<Stealer<Runnable>>>>,
}

impl Drop for Worker {
    fn drop(&mut self) {
        TLS.with(|v| v.borrow_mut().take());
        self.stealers.write().unwrap().remove(self.worker_id);
        while let Some(task) = self.local_queue.pop() {
            self.global_queue.push(task);
        }
    }
}

impl Worker {
    /// Runs this worker.
    #[inline]
    pub async fn run(&mut self) {
        static SMOLSCALE_ALWAYS_STEAL: Lazy<bool> =
            Lazy::new(|| std::env::var("SMOLSCALE_ALWAYS_STEAL").is_ok());

        self.set_tls();
        // let mut is_global = true;
        loop {
            for _ in 0..200 {
                self.set_tls();
                TLS.with(|tls| {
                    if let Some(tls) = tls.borrow_mut().as_mut() {
                        for task in tls.inner_sender.drain(0..) {
                            self.local_queue.push(task);
                        }
                    }
                });

                while let Some((task, _is_stolen)) = self.run_once() {
                    if task.run() {
                        let _ = self.global_notifier.try_send(());
                    }
                    // let _ = self.global_notifier.try_send(());
                    // // sibling notification
                    // // if is_global || *SMOLSCALE_ALWAYS_STEAL {
                    // //     // eprintln!("SIBLING {}", iteration);
                    // //     let _ = self.global_notifier.try_send(());
                    // // } else {
                    // //     // eprintln!("no sib");
                    // // }
                    // if task.run() {
                    //     // let _ = self.global_notifier.try_send(());
                    // }
                }

                let local = self.local_notifier.wait();
                async {
                    local.await;
                    false
                }
                .or(async {
                    self.global_notifier.receive().await.unwrap();
                    true
                })
                .await;
                self.local_notifier.reset();
            }
            futures_lite::future::yield_now().await;
        }
    }

    #[inline]
    fn run_once(&mut self) -> Option<(Runnable, bool)> {
        if let Some(task) = self.local_queue.pop() {
            return Some((task, false));
        }
        self.steal_global();
        // we do work stealing here
        let stealers = self.stealers.read().unwrap();
        let mut stealers: Vec<&Stealer<_>> = stealers.iter().map(|(_, s)| s).collect();
        fastrand::shuffle(&mut stealers);
        for stealer in stealers {
            if let Steal::Success(some) = stealer.steal_batch_and_pop(&self.local_queue) {
                return Some((some, true));
            }
        }
        None
    }

    #[inline]
    fn steal_global(&mut self) -> bool {
        loop {
            match self.global_queue.steal_batch(&self.local_queue) {
                Steal::Empty => return false,
                Steal::Success(_) => return true,
                Steal::Retry => (),
            }
        }
    }

    #[inline]
    fn set_tls(&mut self) {
        TLS.with(|f| {
            let mut f = f.borrow_mut();
            if f.is_none() {
                *f = Some(TlsState {
                    inner_sender: Vec::new(),
                    local_notifier: self.local_notifier.clone(),
                    global_queue: self.global_queue.clone(),
                });
            }
        })
    }
}