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
use std::{
collections::VecDeque,
sync::{Arc, Condvar, Mutex, atomic::AtomicBool},
};
/// A work-stealing queue that supports multiple workers taking work from a shared queue.
///
/// Will be removed once core::sync::mpsc is stable.
pub(crate) struct WorkStealingQueue<T> {
inner: Arc<Inner<T>>,
}
struct Inner<T> {
queue: Mutex<VecDeque<T>>,
condvar: Condvar,
closed: AtomicBool,
}
impl<T> WorkStealingQueue<T> {
/// Creates a new work-stealing queue.
pub(crate) fn new() -> Self {
Self {
inner: Arc::new(Inner {
queue: Mutex::new(VecDeque::new()),
condvar: Condvar::new(),
closed: AtomicBool::new(false),
}),
}
}
/// Creates a worker handle that can steal work from this queue.
pub(crate) fn worker(&self) -> WorkerHandle<T> {
WorkerHandle {
inner: Arc::clone(&self.inner),
}
}
/// Pushes work to the queue. Returns false if the queue is closed.
pub(crate) fn push(&self, item: T) -> bool {
if self
.inner
.closed
.load(core::sync::atomic::Ordering::Acquire)
{
return false;
}
{
let mut queue = self.inner.queue.lock().unwrap();
queue.push_back(item);
}
// Notify one waiting worker.
self.inner.condvar.notify_one();
true
}
/// Closes the queue, preventing new work from being added.
/// Workers will continue to process remaining work until the queue is empty.
pub(crate) fn close(&self) {
self.inner
.closed
.store(true, core::sync::atomic::Ordering::Release);
// Wake up all waiting workers so they can check the closed status.
self.inner.condvar.notify_all();
}
/// Returns the current number of items in the queue.
pub(crate) fn len(&self) -> usize {
self.inner.queue.lock().unwrap().len()
}
}
impl<T> Default for WorkStealingQueue<T> {
fn default() -> Self {
Self::new()
}
}
/// A handle for workers to steal work from the queue.
pub(crate) struct WorkerHandle<T> {
inner: Arc<Inner<T>>,
}
impl<T> WorkerHandle<T> {
/// Attempts to steal work from the queue. Blocks until work is available or the queue is closed.
/// Returns `None` if the queue is closed and empty.
pub(crate) fn steal(&self) -> Option<T> {
let mut queue = self.inner.queue.lock().unwrap();
loop {
// Try to get work
if let Some(item) = queue.pop_front() {
return Some(item);
}
// Check if queue is closed
if self
.inner
.closed
.load(core::sync::atomic::Ordering::Acquire)
{
return None;
}
// Wait for new work or closure
queue = self.inner.condvar.wait(queue).unwrap();
}
}
}
impl<T> Clone for WorkerHandle<T> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
}
}
}
#[cfg(test)]
mod tests {
use std::{thread, time::Duration};
use super::*;
#[test]
fn test_blocking_behavior() {
let queue = WorkStealingQueue::new();
let worker = queue.worker();
let queue_clone = WorkStealingQueue {
inner: Arc::clone(&queue.inner),
};
thread::spawn(move || {
thread::sleep(Duration::from_millis(50));
queue_clone.push(42);
queue_clone.close();
});
assert_eq!(worker.steal(), Some(42));
assert_eq!(worker.steal(), None);
}
}