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::{self, 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, ()> }
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 for Packets {
323 type Item = *mut Handle<'static, ()>;
325 fn next(&mut self) -> Option<*mut Handle<'static, ()>> {
326 if self.cur.is_null() {
329 let ret = Some(self.cur);
330 unsafe { self.cur = (*self.cur).next; }
337 #[allow(unused_imports)]
344 // Don't use the libstd version so we can pull in the right Select structure
345 // (std::comm points at the wrong one)
346 macro_rules! select {
348 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
350 let sel = Select::new();
351 $( let mut $rx = sel.handle(&$rx); )+
355 let ret = sel.wait();
356 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
363 let (tx1, rx1) = channel::<int>();
364 let (tx2, rx2) = channel::<int>();
365 tx1.send(1).unwrap();
367 foo = rx1.recv() => { assert_eq!(foo.unwrap(), 1); },
368 _bar = rx2.recv() => { panic!() }
370 tx2.send(2).unwrap();
372 _foo = rx1.recv() => { panic!() },
373 bar = rx2.recv() => { assert_eq!(bar.unwrap(), 2) }
377 foo = rx1.recv() => { assert!(foo.is_err()); },
378 _bar = rx2.recv() => { panic!() }
382 bar = rx2.recv() => { assert!(bar.is_err()); }
388 let (_tx1, rx1) = channel::<int>();
389 let (_tx2, rx2) = channel::<int>();
390 let (_tx3, rx3) = channel::<int>();
391 let (_tx4, rx4) = channel::<int>();
392 let (tx5, rx5) = channel::<int>();
393 tx5.send(4).unwrap();
395 _foo = rx1.recv() => { panic!("1") },
396 _foo = rx2.recv() => { panic!("2") },
397 _foo = rx3.recv() => { panic!("3") },
398 _foo = rx4.recv() => { panic!("4") },
399 foo = rx5.recv() => { assert_eq!(foo.unwrap(), 4); }
405 let (_tx1, rx1) = channel::<int>();
406 let (tx2, rx2) = channel::<int>();
410 _a1 = rx1.recv() => { panic!() },
411 a2 = rx2.recv() => { assert!(a2.is_err()); }
417 let (tx1, rx1) = channel::<int>();
418 let (_tx2, rx2) = channel::<int>();
419 let (tx3, rx3) = channel::<int>();
421 let _t = Thread::spawn(move|| {
422 for _ in range(0u, 20) { Thread::yield_now(); }
423 tx1.send(1).unwrap();
425 for _ in range(0u, 20) { Thread::yield_now(); }
429 a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
430 _b = rx2.recv() => { panic!() }
432 tx3.send(1).unwrap();
434 a = rx1.recv() => { assert!(a.is_err()) },
435 _b = rx2.recv() => { panic!() }
441 let (tx1, rx1) = channel::<int>();
442 let (tx2, rx2) = channel::<int>();
443 let (tx3, rx3) = channel::<()>();
445 let _t = Thread::spawn(move|| {
446 for _ in range(0u, 20) { Thread::yield_now(); }
447 tx1.send(1).unwrap();
448 tx2.send(2).unwrap();
453 a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
454 a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
457 a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
458 a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
460 assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
461 assert_eq!(rx2.try_recv(), Err(TryRecvError::Empty));
462 tx3.send(()).unwrap();
467 static AMT: int = 10000;
468 let (tx1, rx1) = channel::<int>();
469 let (tx2, rx2) = channel::<int>();
470 let (tx3, rx3) = channel::<()>();
472 let _t = Thread::spawn(move|| {
473 for i in range(0, AMT) {
475 tx1.send(i).unwrap();
477 tx2.send(i).unwrap();
483 for i in range(0, AMT) {
485 i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1.unwrap()); },
486 i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2.unwrap()); }
488 tx3.send(()).unwrap();
494 let (tx1, rx1) = channel::<int>();
495 let (_tx2, rx2) = channel::<int>();
496 let (tx3, rx3) = channel::<()>();
498 let _t = Thread::spawn(move|| {
501 assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
502 tx1.send(2).unwrap();
506 tx3.send(()).unwrap();
508 _i1 = rx1.recv() => {},
509 _i2 = rx2.recv() => panic!()
511 tx3.send(()).unwrap();
516 let (tx1, rx1) = channel::<int>();
517 let (_tx2, rx2) = channel::<int>();
518 let (tx3, rx3) = channel::<()>();
520 let _t = Thread::spawn(move|| {
523 assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
524 tx1.send(2).unwrap();
528 tx3.send(()).unwrap();
530 _i1 = rx1.recv() => {},
531 _i2 = rx2.recv() => panic!()
533 tx3.send(()).unwrap();
538 let (tx1, rx1) = channel::<()>();
539 let (tx2, rx2) = channel::<()>();
540 let (tx3, rx3) = channel::<()>();
541 let _t = Thread::spawn(move|| {
542 let s = Select::new();
543 let mut h1 = s.handle(&rx1);
544 let mut h2 = s.handle(&rx2);
547 assert_eq!(s.wait(), h2.id);
548 tx3.send(()).unwrap();
551 for _ in range(0u, 1000) { Thread::yield_now(); }
553 tx2.send(()).unwrap();
559 let (tx, rx) = channel();
560 tx.send(()).unwrap();
568 let (tx, rx) = channel();
569 tx.send(()).unwrap();
570 tx.send(()).unwrap();
578 let (tx, rx) = channel();
580 tx.send(()).unwrap();
588 let (tx, rx) = channel();
589 tx.send(()).unwrap();
590 let s = Select::new();
591 let mut h = s.handle(&rx);
593 assert_eq!(s.wait2(false), h.id);
598 let (tx, rx) = channel();
599 tx.send(()).unwrap();
600 tx.send(()).unwrap();
601 let s = Select::new();
602 let mut h = s.handle(&rx);
604 assert_eq!(s.wait2(false), h.id);
609 let (tx, rx) = channel();
611 tx.send(()).unwrap();
612 let s = Select::new();
613 let mut h = s.handle(&rx);
615 assert_eq!(s.wait2(false), h.id);
620 let (tx, rx) = channel::<()>();
622 let s = Select::new();
623 let mut h = s.handle(&rx);
625 assert_eq!(s.wait2(false), h.id);
630 let (tx, rx) = channel();
631 tx.send(()).unwrap();
634 let s = Select::new();
635 let mut h = s.handle(&rx);
637 assert_eq!(s.wait2(false), h.id);
642 let (tx, rx) = channel();
644 tx.send(()).unwrap();
647 let s = Select::new();
648 let mut h = s.handle(&rx);
650 assert_eq!(s.wait2(false), h.id);
654 fn oneshot_data_waiting() {
655 let (tx1, rx1) = channel();
656 let (tx2, rx2) = channel();
657 let _t = Thread::spawn(move|| {
659 _n = rx1.recv() => {}
661 tx2.send(()).unwrap();
664 for _ in range(0u, 100) { Thread::yield_now() }
665 tx1.send(()).unwrap();
670 fn stream_data_waiting() {
671 let (tx1, rx1) = channel();
672 let (tx2, rx2) = channel();
673 tx1.send(()).unwrap();
674 tx1.send(()).unwrap();
677 let _t = Thread::spawn(move|| {
679 _n = rx1.recv() => {}
681 tx2.send(()).unwrap();
684 for _ in range(0u, 100) { Thread::yield_now() }
685 tx1.send(()).unwrap();
690 fn shared_data_waiting() {
691 let (tx1, rx1) = channel();
692 let (tx2, rx2) = channel();
694 tx1.send(()).unwrap();
696 let _t = Thread::spawn(move|| {
698 _n = rx1.recv() => {}
700 tx2.send(()).unwrap();
703 for _ in range(0u, 100) { Thread::yield_now() }
704 tx1.send(()).unwrap();
710 let (tx, rx) = sync_channel::<int>(1);
713 n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
719 let (tx, rx) = sync_channel::<int>(0);
720 let _t = Thread::spawn(move|| {
721 for _ in range(0u, 100) { Thread::yield_now() }
725 n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
731 let (tx1, rx1) = sync_channel::<int>(0);
732 let (tx2, rx2): (Sender<int>, Receiver<int>) = channel();
733 let _t = Thread::spawn(move|| { tx1.send(1).unwrap(); });
734 let _t = Thread::spawn(move|| { tx2.send(2).unwrap(); });
739 assert_eq!(rx2.recv().unwrap(), 2);
744 assert_eq!(rx1.recv().unwrap(), 1);