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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use park::DefaultPark;
use worker::WorkerId;

use std::cell::UnsafeCell;
use std::fmt;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Relaxed};
use std::time::{Duration, Instant};

/// State associated with a thread in the thread pool.
///
/// The pool manages a number of threads. Some of those threads are considered
/// "primary" threads and process the work queue. When a task being run on a
/// primary thread enters a blocking context, the responsibility of processing
/// the work queue must be handed off to another thread. This is done by first
/// checking for idle threads on the backup stack. If one is found, the worker
/// token (`WorkerId`) is handed off to that running thread. If none are found,
/// a new thread is spawned.
///
/// This state manages the exchange. A thread that is idle, not assigned to a
/// work queue, sits around for a specified amount of time. When the worker
/// token is handed off, it is first stored in `handoff`. The backup thread is
/// then signaled. At this point, the backup thread wakes up from sleep and
/// reads `handoff`. At that point, it has been promoted to a primary thread and
/// will begin processing inbound work on the work queue.
///
/// The name `Backup` isn't really great for what the type does, but I have not
/// come up with a better name... Maybe it should just be named `Thread`.
#[derive(Debug)]
pub(crate) struct Backup {
    /// Worker ID that is being handed to this thread.
    handoff: UnsafeCell<Option<WorkerId>>,

    /// Thread state.
    ///
    /// This tracks:
    ///
    /// * Is queued flag
    /// * If the pool is shutting down.
    /// * If the thread is running
    state: AtomicUsize,

    /// Next entry in the Treiber stack.
    next_sleeper: UnsafeCell<BackupId>,

    /// Used to put the thread to sleep
    park: DefaultPark,
}

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub(crate) struct BackupId(pub(crate) usize);

#[derive(Debug)]
pub(crate) enum Handoff {
    Worker(WorkerId),
    Idle,
    Terminated,
}

/// Tracks thread state.
#[derive(Clone, Copy, Eq, PartialEq)]
struct State(usize);

/// Set when the worker is pushed onto the scheduler's stack of sleeping
/// threads.
///
/// This flag also serves as a "notification" bit. If another thread is
/// attempting to hand off a worker to the backup thread, then the pushed bit
/// will not be set when the thread tries to shutdown.
pub const PUSHED: usize = 0b001;

/// Set when the thread is running
pub const RUNNING: usize = 0b010;

/// Set when the thread pool has terminated
pub const TERMINATED: usize = 0b100;

// ===== impl Backup =====

impl Backup {
    pub fn new() -> Backup {
        Backup {
            handoff: UnsafeCell::new(None),
            state: AtomicUsize::new(State::new().into()),
            next_sleeper: UnsafeCell::new(BackupId(0)),
            park: DefaultPark::new(),
        }
    }

    /// Called when the thread is starting
    pub fn start(&self, worker_id: &WorkerId) {
        debug_assert!({
            let state: State = self.state.load(Relaxed).into();

            debug_assert!(!state.is_pushed());
            debug_assert!(state.is_running());
            debug_assert!(!state.is_terminated());

            true
        });

        // The handoff value is equal to `worker_id`
        debug_assert_eq!(unsafe { (*self.handoff.get()).as_ref() }, Some(worker_id));

        unsafe {
            *self.handoff.get() = None;
        }
    }

    pub fn is_running(&self) -> bool {
        let state: State = self.state.load(Relaxed).into();
        state.is_running()
    }

    /// Hands off the worker to a thread.
    ///
    /// Returns `true` if the thread needs to be spawned.
    pub fn worker_handoff(&self, worker_id: WorkerId) -> bool {
        unsafe {
            // The backup worker should not already have been handoff a worker.
            debug_assert!((*self.handoff.get()).is_none());

            // Set the handoff
            *self.handoff.get() = Some(worker_id);
        }

        // This *probably* can just be `Release`... memory orderings, how do
        // they work?
        let prev = State::worker_handoff(&self.state);
        debug_assert!(prev.is_pushed());

        if prev.is_running() {
            // Wakeup the backup thread
            self.park.notify();
            false
        } else {
            true
        }
    }

    /// Terminate the worker
    pub fn signal_stop(&self) {
        let prev: State = self.state.fetch_xor(TERMINATED | PUSHED, AcqRel).into();

        debug_assert!(!prev.is_terminated());
        debug_assert!(prev.is_pushed());

        if prev.is_running() {
            self.park.notify();
        }
    }

    /// Release the worker
    pub fn release(&self) {
        let prev: State = self.state.fetch_xor(RUNNING, AcqRel).into();

        debug_assert!(prev.is_running());
    }

    /// Wait for a worker handoff
    pub fn wait_for_handoff(&self, timeout: Option<Duration>) -> Handoff {
        let sleep_until = timeout.map(|dur| Instant::now() + dur);
        let mut state: State = self.state.load(Acquire).into();

        // Run in a loop since there can be spurious wakeups
        loop {
            if !state.is_pushed() {
                if state.is_terminated() {
                    return Handoff::Terminated;
                }

                let worker_id = unsafe { (*self.handoff.get()).take().expect("no worker handoff") };
                return Handoff::Worker(worker_id);
            }

            match sleep_until {
                None => {
                    self.park.park_sync(None);
                    state = self.state.load(Acquire).into();
                }
                Some(when) => {
                    let now = Instant::now();

                    if now < when {
                        self.park.park_sync(Some(when - now));
                        state = self.state.load(Acquire).into();
                    } else {
                        debug_assert!(state.is_running());

                        // Transition out of running
                        let mut next = state;
                        next.unset_running();

                        let actual = self
                            .state
                            .compare_and_swap(state.into(), next.into(), AcqRel)
                            .into();

                        if actual == state {
                            debug_assert!(!next.is_running());
                            return Handoff::Idle;
                        }

                        state = actual;
                    }
                }
            }
        }
    }

    pub fn is_pushed(&self) -> bool {
        let state: State = self.state.load(Relaxed).into();
        state.is_pushed()
    }

    pub fn set_pushed(&self, ordering: Ordering) {
        let prev: State = self.state.fetch_or(PUSHED, ordering).into();
        debug_assert!(!prev.is_pushed());
    }

    #[inline]
    pub fn next_sleeper(&self) -> BackupId {
        unsafe { *self.next_sleeper.get() }
    }

    #[inline]
    pub fn set_next_sleeper(&self, val: BackupId) {
        unsafe {
            *self.next_sleeper.get() = val;
        }
    }
}

// ===== impl State =====

impl State {
    /// Returns a new, default, thread `State`
    pub fn new() -> State {
        State(0)
    }

    /// Returns true if the thread entry is pushed in the sleeper stack
    pub fn is_pushed(&self) -> bool {
        self.0 & PUSHED == PUSHED
    }

    fn unset_pushed(&mut self) {
        self.0 &= !PUSHED;
    }

    pub fn is_running(&self) -> bool {
        self.0 & RUNNING == RUNNING
    }

    pub fn set_running(&mut self) {
        self.0 |= RUNNING;
    }

    pub fn unset_running(&mut self) {
        self.0 &= !RUNNING;
    }

    pub fn is_terminated(&self) -> bool {
        self.0 & TERMINATED == TERMINATED
    }

    fn worker_handoff(state: &AtomicUsize) -> State {
        let mut curr: State = state.load(Acquire).into();

        loop {
            let mut next = curr;
            next.set_running();
            next.unset_pushed();

            let actual = state
                .compare_and_swap(curr.into(), next.into(), AcqRel)
                .into();

            if actual == curr {
                return curr;
            }

            curr = actual;
        }
    }
}

impl From<usize> for State {
    fn from(src: usize) -> State {
        State(src)
    }
}

impl From<State> for usize {
    fn from(src: State) -> usize {
        src.0
    }
}

impl fmt::Debug for State {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("backup::State")
            .field("is_pushed", &self.is_pushed())
            .field("is_running", &self.is_running())
            .field("is_terminated", &self.is_terminated())
            .finish()
    }
}