-
Notifications
You must be signed in to change notification settings - Fork 16
/
select.rs
382 lines (349 loc) · 12.6 KB
/
select.rs
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use std::cell::RefCell;
use std::collections::btree_map::{BTreeMap, Entry};
use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use rand::{self, Rng};
use {ChannelId, Receiver, Sender, Data};
/// Select encapsulates synchronization on at most one channel operation.
///
/// This type was *specifically built* to work inside a macro like
/// `chan_select!`. As a result, it is extremely unergonomic to use manually
/// without the macro (see the `select_manual` test). Therefore, it is hidden
/// from the public API. It is, in every sense of the word, an implementation
/// detail.
///
/// If we want to expose a select interface not built on a macro then it
/// probably shouldn't be this one. However, doing it in a way that is both
/// ergonomic and hetergeneous is probably tricky.
#[doc(hidden)]
pub struct Select<'c> {
/// A condition variable that is notified when one of the participating
/// channels has a synchronization event.
cond: Arc<Condvar>,
/// A mutex for guarding notification from channels.
cond_mutex: Arc<Mutex<()>>,
/// The set of all arms.
choices: BTreeMap<ChannelId, Box<Choice + 'c>>,
/// Scratch space for quickly shuffling the order in which we try to
/// synchronize an operation in select.
ids: Option<Vec<ChannelId>>,
}
/// The result of adding a send operation to `Select`.
///
/// This exposes a uniform interface with `SelectRecvHandle`. Namely, the id
/// of the underlying channel can be accessed.
#[doc(hidden)]
#[derive(Debug)]
pub struct SelectSendHandle<'s, T: 's> {
chan: &'s Sender<T>,
}
/// The result of adding a recv operation to `Select`.
///
/// This exposes a uniform interface with `SelectRecvHandle`. Namely, the id
/// of the underlying channel can be accessed.
///
/// This also stores a reference to the value that has been received. The
/// value is shared with a `Choice` in `Select`'s map of subscribed channels.
#[doc(hidden)]
#[derive(Debug)]
pub struct SelectRecvHandle<'r, T: 'r> {
chan: &'r Receiver<T>,
val: Rc<RefCell<Option<Option<T>>>>,
}
/// Expose a uniform interface over send and receive operations.
///
/// In particular, this trait is used to *erase* the type parameter in the
/// `Receiver` and `Sender` types. This is essential to building a hetergeneous
/// select.
trait Choice {
/// Subscribe the owning `Select` to the channel in this choice.
fn subscribe(&mut self, mutex: Arc<Mutex<()>>, condvar: Arc<Condvar>);
/// Unsubscribe the owning `Select` from the channel in this choice.
fn unsubscribe(&self);
/// Return the subscription identifier.
fn subscription(&self) -> Option<u64>;
/// Attempt to synchronize.
///
/// Returns `true` if and only if the operation synchronized.
fn try(&mut self) -> bool;
/// Lock the underlying channel.
fn lock(&mut self);
/// Unlock the underlying channel.
fn unlock(&mut self);
}
struct SendChoice<'s, T: 's> {
chan: &'s Sender<T>,
guard: Option<MutexGuard<'s, Data<T>>>,
id: Option<u64>,
val: Option<T>,
}
struct RecvChoice<'r, T: 'r> {
chan: &'r Receiver<T>,
guard: Option<MutexGuard<'r, Data<T>>>,
id: Option<u64>,
val: Rc<RefCell<Option<Option<T>>>>,
}
impl<'c> Select<'c> {
/// Create a new `Select`.
pub fn new() -> Select<'c> {
Select {
cond: Arc::new(Condvar::new()),
cond_mutex: Arc::new(Mutex::new(())),
choices: BTreeMap::new(),
ids: None,
}
}
fn is_subscribed(&self) -> bool {
self.choices.is_empty()
|| self.choices.values().next().unwrap().subscription().is_some()
}
/// Perform a select. Block until exactly one channel operation
/// synchronizes.
pub fn select(&mut self) -> ChannelId {
self.maybe_try_select(false).unwrap()
}
/// Perform a select. If all channel operations are blocked, return `None`.
/// (N.B. This will *never* subscribe to channels.)
pub fn try_select(&mut self) -> Option<ChannelId> {
self.maybe_try_select(true)
}
fn maybe_try_select(&mut self, try: bool) -> Option<ChannelId> {
fn try_sync<'c>(
ids: &mut Option<Vec<ChannelId>>,
choices: &mut BTreeMap<ChannelId, Box<Choice + 'c>>,
) -> Option<ChannelId> {
let mut ids = ids.as_mut().unwrap();
rand::thread_rng().shuffle(ids);
for key in ids {
if choices.get_mut(key).unwrap().try() {
return Some(*key);
}
}
None
}
// This is our initial try. If `try` is `true` (i.e., there is a
// `default` arm), then we quit if the initial try fails.
if self.ids.is_none() {
self.ids = Some(self.choices.keys().cloned().collect());
}
if let Some(key) = try_sync(&mut self.ids, &mut self.choices) {
return Some(key);
}
if try {
return None;
}
// At this point, we've tried to pick one of the
// synchronization events without initiating a subscription,
// but nothing succeeded. Before we sit and wait, we need to
// tell all of our channels to notify us when something
// changes.
if !self.is_subscribed() {
for (_, choice) in &mut self.choices {
choice.subscribe(self.cond_mutex.clone(), self.cond.clone());
}
}
// This is an extremely delicate dance.
//
// The key is that before we do anything, we need to make sure all
// involved channels are synchronized. We achieve this by acquiring
// the mutex inside of each channel.
//
// Once that's done, we can attempt to synchronize at most one of the
// channel operations. If we succeed, then we unlock all of the
// channels and return the id of the choice that synchronized.
//
// If we don't succeed, then we need to block and wait for something
// to happen until we try again. Doing this is tricky.
//
// The key is that when a channel synchronizes, it will notify any
// subscribed `Select` instances because a synchronization means
// something has changed and `Select` should try to synchronize one
// of its channel operations.
//
// However, it is critical that a channel only notify `Select` when
// `Select` is ready to receive notifications. i.e., we must
// synchronize the channel's notification with `Select`'s wait on
// the condition variable.
//
// Therefore, after we've tried synchronization and failed, we need
// to lock `Select`'s mutex *before unlocking the channels*. This
// will prevent channels from trying to notify `Select` before it is
// ready to receive a notification. (If it misses a notification then
// we risk deadlock.)
//
// Once `Select` is locked, we unlock all of the channels, unlock
// the `Select` and block. This guarantees that notifications to this
// `Select` are synchronized with waiting on the condition variable.
//
// Once the condition variable is notified, we repeat the process.
loop {
for (_, choice) in &mut self.choices {
choice.lock();
}
if let Some(key) = try_sync(&mut self.ids, &mut self.choices) {
for (_, choice) in &mut self.choices {
choice.unlock();
}
return Some(key);
}
let cond_lock = self.cond_mutex.lock().unwrap();
for (_, choice) in &mut self.choices {
choice.unlock();
}
drop(self.cond.wait(cond_lock).unwrap());
}
}
/// Register a new send operation with the select.
pub fn send<'s: 'c, T: 'static>(
&mut self,
chan: &'s Sender<T>,
val: T,
) -> SelectSendHandle<'s, T> {
let mut choice = SendChoice {
chan: chan,
guard: None,
id: None,
val: Some(val),
};
match self.choices.entry(chan.id()) {
Entry::Occupied(mut prev_choice) => {
choice.id = prev_choice.get().subscription();
*prev_choice.get_mut() = Box::new(choice);
}
Entry::Vacant(spot) => {
assert!(self.ids.is_none(),
"cannot add new channels after initial select");
spot.insert(Box::new(choice));
}
}
SelectSendHandle { chan: chan }
}
/// Register a new receive operation with the select.
pub fn recv<'r: 'c, T: 'static>(
&mut self,
chan: &'r Receiver<T>,
) -> SelectRecvHandle<'r, T> {
let mut choice = RecvChoice {
chan: chan,
guard: None,
id: None,
val: Rc::new(RefCell::new(None)),
};
let handle_val_loc = choice.val.clone();
match self.choices.entry(chan.id()) {
Entry::Occupied(mut prev_choice) => {
choice.id = prev_choice.get().subscription();
*prev_choice.get_mut() = Box::new(choice);
}
Entry::Vacant(spot) => {
assert!(self.ids.is_none(),
"cannot add new channels after initial select");
spot.insert(Box::new(choice));
}
}
SelectRecvHandle { chan: chan, val: handle_val_loc }
}
}
impl<'c> Drop for Select<'c> {
fn drop(&mut self) {
for (_, choice) in &mut self.choices {
choice.unsubscribe();
}
}
}
impl<'s, T> Choice for SendChoice<'s, T> {
fn subscribe(&mut self, mutex: Arc<Mutex<()>>, condvar: Arc<Condvar>) {
self.id = Some(self.chan.inner().notify.subscribe(mutex, condvar));
}
fn unsubscribe(&self) {
if let Some(id) = self.id {
self.chan.inner().notify.unsubscribe(id)
}
}
fn subscription(&self) -> Option<u64> {
self.id
}
fn try(&mut self) -> bool {
let v = match self.val.take() {
Some(v) => v,
None => return false,
};
// If this choice has been locked, then we need to use that lock
// when trying to synchronize. We must also be careful to put the
// lock back where it was. Dropping it would be disastrous!
let try = match self.guard.take() {
None => self.chan.try_send(v),
Some(g) => {
let op = self.chan.send_op(g, true, v);
let (lock, result) = op.into_result_lock();
self.guard = Some(lock);
result
}
};
match try {
Ok(()) => true,
Err(v) => { self.val = Some(v); false }
}
}
fn lock(&mut self) {
self.guard = Some(self.chan.inner().lock());
}
fn unlock(&mut self) {
self.guard.take();
}
}
impl<'r, T> Choice for RecvChoice<'r, T> {
fn subscribe(&mut self, mutex: Arc<Mutex<()>>, condvar: Arc<Condvar>) {
self.id = Some(self.chan.inner().notify.subscribe(mutex, condvar));
}
fn unsubscribe(&self) {
if let Some(id) = self.id {
self.chan.inner().notify.unsubscribe(id)
}
}
fn subscription(&self) -> Option<u64> {
self.id
}
fn try(&mut self) -> bool {
// If this choice has been locked, then we need to use that lock
// when trying to synchronize. We must also be careful to put the
// lock back where it was. Dropping it would be disastrous!
let try = match self.guard.take() {
None => self.chan.try_recv(),
Some(g) => {
let op = self.chan.recv_op(g, true);
let (lock, result) = op.into_result_lock();
self.guard = Some(lock);
result
}
};
match try {
Ok(v) => { *self.val.borrow_mut() = Some(v); true }
Err(()) => false,
}
}
fn lock(&mut self) {
self.guard = Some(self.chan.inner().lock());
}
fn unlock(&mut self) {
self.guard.take();
}
}
impl<'s, T> SelectSendHandle<'s, T> {
/// Return the id of the underlying channel.
pub fn id(&self) -> ChannelId {
self.chan.id()
}
}
impl<'r, T> SelectRecvHandle<'r, T> {
/// Return the id of the underlying channel.
pub fn id(&self) -> ChannelId {
self.chan.id()
}
/// Return the retrieved value.
///
/// Panics if this channel was not chosen to synchronize.
pub fn into_value(self) -> Option<T> {
self.val.borrow_mut().take().unwrap()
}
}