1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Selection over an array of receivers
13 //! This module contains the implementation machinery necessary for selecting
14 //! over a number of receivers. One large goal of this module is to provide an
15 //! efficient interface to selecting over any receiver of any type.
17 //! This is achieved through an architecture of a "receiver set" in which
18 //! receivers are added to a set and then the entire set is waited on at once.
19 //! The set can be waited on multiple times to prevent re-adding each receiver
22 //! Usage of this module is currently encouraged to go through the use of the
23 //! `select!` macro. This macro allows naturally binding of variables to the
24 //! received values of receivers in a much more natural syntax then usage of the
25 //! `Select` structure directly.
30 //! use std::sync::mpsc::channel;
32 //! let (tx1, rx1) = channel();
33 //! let (tx2, rx2) = channel();
35 //! tx1.send(1i).unwrap();
36 //! tx2.send(2i).unwrap();
39 //! val = rx1.recv() => {
40 //! assert_eq!(val.unwrap(), 1i);
42 //! val = rx2.recv() => {
43 //! assert_eq!(val.unwrap(), 2i);
49 #![experimental = "This implementation, while likely sufficient, is unsafe and \
50 likely to be error prone. At some point in the future this \
51 module will likely be replaced, and it is currently \
52 unknown how much API breakage that will cause. The ability \
53 to select over a number of channels will remain forever, \
54 but no guarantees beyond this are being made"]
60 use core::kinds::marker;
64 use sync::mpsc::{Receiver, RecvError};
65 use sync::mpsc::blocking::{mod, SignalToken};
67 /// The "receiver set" of the select interface. This structure is used to manage
68 /// a set of receivers which are being selected over.
70 head: *mut Handle<'static, ()>,
71 tail: *mut Handle<'static, ()>,
73 marker1: marker::NoSend,
76 /// A handle to a receiver which is currently a member of a `Select` set of
77 /// receivers. This handle is used to keep the receiver in the set as well as
78 /// interact with the underlying receiver.
79 pub struct Handle<'rx, T:'rx> {
80 /// The ID of this handle, used to compare against the return value of
83 selector: &'rx Select,
84 next: *mut Handle<'static, ()>,
85 prev: *mut Handle<'static, ()>,
87 packet: &'rx (Packet+'rx),
89 // due to our fun transmutes, we be sure to place this at the end. (nothing
90 // previous relies on T)
94 struct Packets { cur: *mut Handle<'static, ()> }
97 #[deriving(PartialEq)]
98 pub enum StartResult {
105 fn can_recv(&self) -> bool;
106 fn start_selection(&self, token: SignalToken) -> StartResult;
107 fn abort_selection(&self) -> bool;
111 /// Creates a new selection structure. This set is initially empty and
112 /// `wait` will panic!() if called.
114 /// Usage of this struct directly can sometimes be burdensome, and usage is
115 /// rather much easier through the `select!` macro.
116 pub fn new() -> Select {
118 marker1: marker::NoSend,
119 head: 0 as *mut Handle<'static, ()>,
120 tail: 0 as *mut Handle<'static, ()>,
121 next_id: Cell::new(1),
125 /// Creates a new handle into this receiver set for a new receiver. Note
126 /// that this does *not* add the receiver to the receiver set, for that you
127 /// must call the `add` method on the handle itself.
128 pub fn handle<'a, T: Send>(&'a self, rx: &'a Receiver<T>) -> Handle<'a, T> {
129 let id = self.next_id.get();
130 self.next_id.set(id + 1);
134 next: 0 as *mut Handle<'static, ()>,
135 prev: 0 as *mut Handle<'static, ()>,
142 /// Waits for an event on this receiver set. The returned value is *not* an
143 /// index, but rather an id. This id can be queried against any active
144 /// `Handle` structures (each one has an `id` method). The handle with
145 /// the matching `id` will have some sort of event available on it. The
146 /// event could either be that data is available or the corresponding
147 /// channel has been closed.
148 pub fn wait(&self) -> uint {
152 /// Helper method for skipping the preflight checks during testing
153 fn wait2(&self, do_preflight_checks: bool) -> uint {
154 // Note that this is currently an inefficient implementation. We in
155 // theory have knowledge about all receivers in the set ahead of time,
156 // so this method shouldn't really have to iterate over all of them yet
157 // again. The idea with this "receiver set" interface is to get the
158 // interface right this time around, and later this implementation can
161 // This implementation can be summarized by:
163 // fn select(receivers) {
164 // if any receiver ready { return ready index }
166 // block on all receivers
168 // unblock on all receivers
169 // return ready index
172 // Most notably, the iterations over all of the receivers shouldn't be
175 // Stage 1: preflight checks. Look for any packets ready to receive
176 if do_preflight_checks {
177 for handle in self.iter() {
178 if (*handle).packet.can_recv() {
179 return (*handle).id();
184 // Stage 2: begin the blocking process
186 // Create a number of signal tokens, and install each one
187 // sequentially until one fails. If one fails, then abort the
188 // selection on the already-installed tokens.
189 let (wait_token, signal_token) = blocking::tokens();
190 for (i, handle) in self.iter().enumerate() {
191 match (*handle).packet.start_selection(signal_token.clone()) {
192 StartResult::Installed => {}
193 StartResult::Abort => {
194 // Go back and abort the already-begun selections
195 for handle in self.iter().take(i) {
196 (*handle).packet.abort_selection();
203 // Stage 3: no messages available, actually block
206 // Stage 4: there *must* be message available; find it.
208 // Abort the selection process on each receiver. If the abort
209 // process returns `true`, then that means that the receiver is
210 // ready to receive some data. Note that this also means that the
211 // receiver may have yet to have fully read the `to_wake` field and
212 // woken us up (although the wakeup is guaranteed to fail).
214 // This situation happens in the window of where a sender invokes
215 // increment(), sees -1, and then decides to wake up the task. After
216 // all this is done, the sending thread will set `selecting` to
217 // `false`. Until this is done, we cannot return. If we were to
218 // return, then a sender could wake up a receiver which has gone
219 // back to sleep after this call to `select`.
221 // Note that it is a "fairly small window" in which an increment()
222 // views that it should wake a thread up until the `selecting` bit
223 // is set to false. For now, the implementation currently just spins
224 // in a yield loop. This is very distasteful, but this
225 // implementation is already nowhere near what it should ideally be.
226 // A rewrite should focus on avoiding a yield loop, and for now this
227 // implementation is tying us over to a more efficient "don't
228 // iterate over everything every time" implementation.
229 let mut ready_id = uint::MAX;
230 for handle in self.iter() {
231 if (*handle).packet.abort_selection() {
232 ready_id = (*handle).id;
236 // We must have found a ready receiver
237 assert!(ready_id != uint::MAX);
242 fn iter(&self) -> Packets { Packets { cur: self.head } }
245 impl<'rx, T: Send> Handle<'rx, T> {
246 /// Retrieve the id of this handle.
248 pub fn id(&self) -> uint { self.id }
250 /// Block to receive a value on the underlying receiver, returning `Some` on
251 /// success or `None` if the channel disconnects. This function has the same
252 /// semantics as `Receiver.recv`
253 pub fn recv(&mut self) -> Result<T, RecvError> { self.rx.recv() }
255 /// Adds this handle to the receiver set that the handle was created from. This
256 /// method can be called multiple times, but it has no effect if `add` was
257 /// called previously.
259 /// This method is unsafe because it requires that the `Handle` is not moved
260 /// while it is added to the `Select` set.
261 pub unsafe fn add(&mut self) {
262 if self.added { return }
263 let selector: &mut Select = mem::transmute(&*self.selector);
264 let me: *mut Handle<'static, ()> = mem::transmute(&*self);
266 if selector.head.is_null() {
270 (*me).prev = selector.tail;
271 assert!((*me).next.is_null());
272 (*selector.tail).next = me;
278 /// Removes this handle from the `Select` set. This method is unsafe because
279 /// it has no guarantee that the `Handle` was not moved since `add` was
281 pub unsafe fn remove(&mut self) {
282 if !self.added { return }
284 let selector: &mut Select = mem::transmute(&*self.selector);
285 let me: *mut Handle<'static, ()> = mem::transmute(&*self);
287 if self.prev.is_null() {
288 assert_eq!(selector.head, me);
289 selector.head = self.next;
291 (*self.prev).next = self.next;
293 if self.next.is_null() {
294 assert_eq!(selector.tail, me);
295 selector.tail = self.prev;
297 (*self.next).prev = self.prev;
300 self.next = 0 as *mut Handle<'static, ()>;
301 self.prev = 0 as *mut Handle<'static, ()>;
308 impl Drop for Select {
310 assert!(self.head.is_null());
311 assert!(self.tail.is_null());
316 impl<'rx, T: Send> Drop for Handle<'rx, T> {
318 unsafe { self.remove() }
322 impl Iterator<*mut Handle<'static, ()>> for Packets {
323 fn next(&mut self) -> Option<*mut Handle<'static, ()>> {
324 if self.cur.is_null() {
327 let ret = Some(self.cur);
328 unsafe { self.cur = (*self.cur).next; }
335 #[allow(unused_imports)]
342 // Don't use the libstd version so we can pull in the right Select structure
343 // (std::comm points at the wrong one)
344 macro_rules! select {
346 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
348 let sel = Select::new();
349 $( let mut $rx = sel.handle(&$rx); )+
353 let ret = sel.wait();
354 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
361 let (tx1, rx1) = channel::<int>();
362 let (tx2, rx2) = channel::<int>();
363 tx1.send(1).unwrap();
365 foo = rx1.recv() => { assert_eq!(foo.unwrap(), 1); },
366 _bar = rx2.recv() => { panic!() }
368 tx2.send(2).unwrap();
370 _foo = rx1.recv() => { panic!() },
371 bar = rx2.recv() => { assert_eq!(bar.unwrap(), 2) }
375 foo = rx1.recv() => { assert!(foo.is_err()); },
376 _bar = rx2.recv() => { panic!() }
380 bar = rx2.recv() => { assert!(bar.is_err()); }
386 let (_tx1, rx1) = channel::<int>();
387 let (_tx2, rx2) = channel::<int>();
388 let (_tx3, rx3) = channel::<int>();
389 let (_tx4, rx4) = channel::<int>();
390 let (tx5, rx5) = channel::<int>();
391 tx5.send(4).unwrap();
393 _foo = rx1.recv() => { panic!("1") },
394 _foo = rx2.recv() => { panic!("2") },
395 _foo = rx3.recv() => { panic!("3") },
396 _foo = rx4.recv() => { panic!("4") },
397 foo = rx5.recv() => { assert_eq!(foo.unwrap(), 4); }
403 let (_tx1, rx1) = channel::<int>();
404 let (tx2, rx2) = channel::<int>();
408 _a1 = rx1.recv() => { panic!() },
409 a2 = rx2.recv() => { assert!(a2.is_err()); }
415 let (tx1, rx1) = channel::<int>();
416 let (_tx2, rx2) = channel::<int>();
417 let (tx3, rx3) = channel::<int>();
419 let _t = Thread::spawn(move|| {
420 for _ in range(0u, 20) { Thread::yield_now(); }
421 tx1.send(1).unwrap();
423 for _ in range(0u, 20) { Thread::yield_now(); }
427 a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
428 _b = rx2.recv() => { panic!() }
430 tx3.send(1).unwrap();
432 a = rx1.recv() => { assert!(a.is_err()) },
433 _b = rx2.recv() => { panic!() }
439 let (tx1, rx1) = channel::<int>();
440 let (tx2, rx2) = channel::<int>();
441 let (tx3, rx3) = channel::<()>();
443 let _t = Thread::spawn(move|| {
444 for _ in range(0u, 20) { Thread::yield_now(); }
445 tx1.send(1).unwrap();
446 tx2.send(2).unwrap();
451 a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
452 a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
455 a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
456 a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
458 assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
459 assert_eq!(rx2.try_recv(), Err(TryRecvError::Empty));
460 tx3.send(()).unwrap();
465 static AMT: int = 10000;
466 let (tx1, rx1) = channel::<int>();
467 let (tx2, rx2) = channel::<int>();
468 let (tx3, rx3) = channel::<()>();
470 let _t = Thread::spawn(move|| {
471 for i in range(0, AMT) {
473 tx1.send(i).unwrap();
475 tx2.send(i).unwrap();
481 for i in range(0, AMT) {
483 i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1.unwrap()); },
484 i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2.unwrap()); }
486 tx3.send(()).unwrap();
492 let (tx1, rx1) = channel::<int>();
493 let (_tx2, rx2) = channel::<int>();
494 let (tx3, rx3) = channel::<()>();
496 let _t = Thread::spawn(move|| {
499 assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
500 tx1.send(2).unwrap();
504 tx3.send(()).unwrap();
506 _i1 = rx1.recv() => {},
507 _i2 = rx2.recv() => panic!()
509 tx3.send(()).unwrap();
514 let (tx1, rx1) = channel::<int>();
515 let (_tx2, rx2) = channel::<int>();
516 let (tx3, rx3) = channel::<()>();
518 let _t = Thread::spawn(move|| {
521 assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
522 tx1.send(2).unwrap();
526 tx3.send(()).unwrap();
528 _i1 = rx1.recv() => {},
529 _i2 = rx2.recv() => panic!()
531 tx3.send(()).unwrap();
536 let (tx1, rx1) = channel::<()>();
537 let (tx2, rx2) = channel::<()>();
538 let (tx3, rx3) = channel::<()>();
539 let _t = Thread::spawn(move|| {
540 let s = Select::new();
541 let mut h1 = s.handle(&rx1);
542 let mut h2 = s.handle(&rx2);
545 assert_eq!(s.wait(), h2.id);
546 tx3.send(()).unwrap();
549 for _ in range(0u, 1000) { Thread::yield_now(); }
551 tx2.send(()).unwrap();
557 let (tx, rx) = channel();
558 tx.send(()).unwrap();
566 let (tx, rx) = channel();
567 tx.send(()).unwrap();
568 tx.send(()).unwrap();
576 let (tx, rx) = channel();
578 tx.send(()).unwrap();
586 let (tx, rx) = channel();
587 tx.send(()).unwrap();
588 let s = Select::new();
589 let mut h = s.handle(&rx);
591 assert_eq!(s.wait2(false), h.id);
596 let (tx, rx) = channel();
597 tx.send(()).unwrap();
598 tx.send(()).unwrap();
599 let s = Select::new();
600 let mut h = s.handle(&rx);
602 assert_eq!(s.wait2(false), h.id);
607 let (tx, rx) = channel();
609 tx.send(()).unwrap();
610 let s = Select::new();
611 let mut h = s.handle(&rx);
613 assert_eq!(s.wait2(false), h.id);
618 let (tx, rx) = channel::<()>();
620 let s = Select::new();
621 let mut h = s.handle(&rx);
623 assert_eq!(s.wait2(false), h.id);
628 let (tx, rx) = channel();
629 tx.send(()).unwrap();
632 let s = Select::new();
633 let mut h = s.handle(&rx);
635 assert_eq!(s.wait2(false), h.id);
640 let (tx, rx) = channel();
642 tx.send(()).unwrap();
645 let s = Select::new();
646 let mut h = s.handle(&rx);
648 assert_eq!(s.wait2(false), h.id);
652 fn oneshot_data_waiting() {
653 let (tx1, rx1) = channel();
654 let (tx2, rx2) = channel();
655 let _t = Thread::spawn(move|| {
657 _n = rx1.recv() => {}
659 tx2.send(()).unwrap();
662 for _ in range(0u, 100) { Thread::yield_now() }
663 tx1.send(()).unwrap();
668 fn stream_data_waiting() {
669 let (tx1, rx1) = channel();
670 let (tx2, rx2) = channel();
671 tx1.send(()).unwrap();
672 tx1.send(()).unwrap();
675 let _t = Thread::spawn(move|| {
677 _n = rx1.recv() => {}
679 tx2.send(()).unwrap();
682 for _ in range(0u, 100) { Thread::yield_now() }
683 tx1.send(()).unwrap();
688 fn shared_data_waiting() {
689 let (tx1, rx1) = channel();
690 let (tx2, rx2) = channel();
692 tx1.send(()).unwrap();
694 let _t = Thread::spawn(move|| {
696 _n = rx1.recv() => {}
698 tx2.send(()).unwrap();
701 for _ in range(0u, 100) { Thread::yield_now() }
702 tx1.send(()).unwrap();
708 let (tx, rx) = sync_channel::<int>(1);
711 n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
717 let (tx, rx) = sync_channel::<int>(0);
718 let _t = Thread::spawn(move|| {
719 for _ in range(0u, 100) { Thread::yield_now() }
723 n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
729 let (tx1, rx1) = sync_channel::<int>(0);
730 let (tx2, rx2): (Sender<int>, Receiver<int>) = channel();
731 let _t = Thread::spawn(move|| { tx1.send(1).unwrap(); });
732 let _t = Thread::spawn(move|| { tx2.send(2).unwrap(); });
737 assert_eq!(rx2.recv().unwrap(), 2);
742 assert_eq!(rx1.recv().unwrap(), 1);