]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mpsc/select.rs
Auto merge of #36341 - sagebind:thread_id, r=alexcrichton
[rust.git] / src / libstd / sync / mpsc / select.rs
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.
4 //
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.
10
11 //! Selection over an array of receivers
12 //!
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.
16 //!
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
20 //! to the set.
21 //!
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.
26 //!
27 //! # Examples
28 //!
29 //! ```rust
30 //! #![feature(mpsc_select)]
31 //!
32 //! use std::sync::mpsc::channel;
33 //!
34 //! let (tx1, rx1) = channel();
35 //! let (tx2, rx2) = channel();
36 //!
37 //! tx1.send(1).unwrap();
38 //! tx2.send(2).unwrap();
39 //!
40 //! select! {
41 //!     val = rx1.recv() => {
42 //!         assert_eq!(val.unwrap(), 1);
43 //!     },
44 //!     val = rx2.recv() => {
45 //!         assert_eq!(val.unwrap(), 2);
46 //!     }
47 //! }
48 //! ```
49
50 #![allow(dead_code)]
51 #![unstable(feature = "mpsc_select",
52             reason = "This implementation, while likely sufficient, is unsafe and \
53                       likely to be error prone. At some point in the future this \
54                       module will likely be replaced, and it is currently \
55                       unknown how much API breakage that will cause. The ability \
56                       to select over a number of channels will remain forever, \
57                       but no guarantees beyond this are being made",
58             issue = "27800")]
59
60
61 use fmt;
62
63 use core::cell::{Cell, UnsafeCell};
64 use core::marker;
65 use core::ptr;
66 use core::usize;
67
68 use sync::mpsc::{Receiver, RecvError};
69 use sync::mpsc::blocking::{self, SignalToken};
70
71 /// The "receiver set" of the select interface. This structure is used to manage
72 /// a set of receivers which are being selected over.
73 pub struct Select {
74     inner: UnsafeCell<SelectInner>,
75     next_id: Cell<usize>,
76 }
77
78 struct SelectInner {
79     head: *mut Handle<'static, ()>,
80     tail: *mut Handle<'static, ()>,
81 }
82
83 impl !marker::Send for Select {}
84
85 /// A handle to a receiver which is currently a member of a `Select` set of
86 /// receivers.  This handle is used to keep the receiver in the set as well as
87 /// interact with the underlying receiver.
88 pub struct Handle<'rx, T:Send+'rx> {
89     /// The ID of this handle, used to compare against the return value of
90     /// `Select::wait()`
91     id: usize,
92     selector: *mut SelectInner,
93     next: *mut Handle<'static, ()>,
94     prev: *mut Handle<'static, ()>,
95     added: bool,
96     packet: &'rx (Packet+'rx),
97
98     // due to our fun transmutes, we be sure to place this at the end. (nothing
99     // previous relies on T)
100     rx: &'rx Receiver<T>,
101 }
102
103 struct Packets { cur: *mut Handle<'static, ()> }
104
105 #[doc(hidden)]
106 #[derive(PartialEq, Eq)]
107 pub enum StartResult {
108     Installed,
109     Abort,
110 }
111
112 #[doc(hidden)]
113 pub trait Packet {
114     fn can_recv(&self) -> bool;
115     fn start_selection(&self, token: SignalToken) -> StartResult;
116     fn abort_selection(&self) -> bool;
117 }
118
119 impl Select {
120     /// Creates a new selection structure. This set is initially empty.
121     ///
122     /// Usage of this struct directly can sometimes be burdensome, and usage is much easier through
123     /// the `select!` macro.
124     ///
125     /// # Examples
126     ///
127     /// ```
128     /// #![feature(mpsc_select)]
129     ///
130     /// use std::sync::mpsc::Select;
131     ///
132     /// let select = Select::new();
133     /// ```
134     pub fn new() -> Select {
135         Select {
136             inner: UnsafeCell::new(SelectInner {
137                 head: ptr::null_mut(),
138                 tail: ptr::null_mut(),
139             }),
140             next_id: Cell::new(1),
141         }
142     }
143
144     /// Creates a new handle into this receiver set for a new receiver. Note
145     /// that this does *not* add the receiver to the receiver set, for that you
146     /// must call the `add` method on the handle itself.
147     pub fn handle<'a, T: Send>(&'a self, rx: &'a Receiver<T>) -> Handle<'a, T> {
148         let id = self.next_id.get();
149         self.next_id.set(id + 1);
150         Handle {
151             id: id,
152             selector: self.inner.get(),
153             next: ptr::null_mut(),
154             prev: ptr::null_mut(),
155             added: false,
156             rx: rx,
157             packet: rx,
158         }
159     }
160
161     /// Waits for an event on this receiver set. The returned value is *not* an
162     /// index, but rather an id. This id can be queried against any active
163     /// `Handle` structures (each one has an `id` method). The handle with
164     /// the matching `id` will have some sort of event available on it. The
165     /// event could either be that data is available or the corresponding
166     /// channel has been closed.
167     pub fn wait(&self) -> usize {
168         self.wait2(true)
169     }
170
171     /// Helper method for skipping the preflight checks during testing
172     fn wait2(&self, do_preflight_checks: bool) -> usize {
173         // Note that this is currently an inefficient implementation. We in
174         // theory have knowledge about all receivers in the set ahead of time,
175         // so this method shouldn't really have to iterate over all of them yet
176         // again. The idea with this "receiver set" interface is to get the
177         // interface right this time around, and later this implementation can
178         // be optimized.
179         //
180         // This implementation can be summarized by:
181         //
182         //      fn select(receivers) {
183         //          if any receiver ready { return ready index }
184         //          deschedule {
185         //              block on all receivers
186         //          }
187         //          unblock on all receivers
188         //          return ready index
189         //      }
190         //
191         // Most notably, the iterations over all of the receivers shouldn't be
192         // necessary.
193         unsafe {
194             // Stage 1: preflight checks. Look for any packets ready to receive
195             if do_preflight_checks {
196                 for handle in self.iter() {
197                     if (*handle).packet.can_recv() {
198                         return (*handle).id();
199                     }
200                 }
201             }
202
203             // Stage 2: begin the blocking process
204             //
205             // Create a number of signal tokens, and install each one
206             // sequentially until one fails. If one fails, then abort the
207             // selection on the already-installed tokens.
208             let (wait_token, signal_token) = blocking::tokens();
209             for (i, handle) in self.iter().enumerate() {
210                 match (*handle).packet.start_selection(signal_token.clone()) {
211                     StartResult::Installed => {}
212                     StartResult::Abort => {
213                         // Go back and abort the already-begun selections
214                         for handle in self.iter().take(i) {
215                             (*handle).packet.abort_selection();
216                         }
217                         return (*handle).id;
218                     }
219                 }
220             }
221
222             // Stage 3: no messages available, actually block
223             wait_token.wait();
224
225             // Stage 4: there *must* be message available; find it.
226             //
227             // Abort the selection process on each receiver. If the abort
228             // process returns `true`, then that means that the receiver is
229             // ready to receive some data. Note that this also means that the
230             // receiver may have yet to have fully read the `to_wake` field and
231             // woken us up (although the wakeup is guaranteed to fail).
232             //
233             // This situation happens in the window of where a sender invokes
234             // increment(), sees -1, and then decides to wake up the thread. After
235             // all this is done, the sending thread will set `selecting` to
236             // `false`. Until this is done, we cannot return. If we were to
237             // return, then a sender could wake up a receiver which has gone
238             // back to sleep after this call to `select`.
239             //
240             // Note that it is a "fairly small window" in which an increment()
241             // views that it should wake a thread up until the `selecting` bit
242             // is set to false. For now, the implementation currently just spins
243             // in a yield loop. This is very distasteful, but this
244             // implementation is already nowhere near what it should ideally be.
245             // A rewrite should focus on avoiding a yield loop, and for now this
246             // implementation is tying us over to a more efficient "don't
247             // iterate over everything every time" implementation.
248             let mut ready_id = usize::MAX;
249             for handle in self.iter() {
250                 if (*handle).packet.abort_selection() {
251                     ready_id = (*handle).id;
252                 }
253             }
254
255             // We must have found a ready receiver
256             assert!(ready_id != usize::MAX);
257             return ready_id;
258         }
259     }
260
261     fn iter(&self) -> Packets { Packets { cur: unsafe { &*self.inner.get() }.head } }
262 }
263
264 impl<'rx, T: Send> Handle<'rx, T> {
265     /// Retrieves the id of this handle.
266     #[inline]
267     pub fn id(&self) -> usize { self.id }
268
269     /// Blocks to receive a value on the underlying receiver, returning `Some` on
270     /// success or `None` if the channel disconnects. This function has the same
271     /// semantics as `Receiver.recv`
272     pub fn recv(&mut self) -> Result<T, RecvError> { self.rx.recv() }
273
274     /// Adds this handle to the receiver set that the handle was created from. This
275     /// method can be called multiple times, but it has no effect if `add` was
276     /// called previously.
277     ///
278     /// This method is unsafe because it requires that the `Handle` is not moved
279     /// while it is added to the `Select` set.
280     pub unsafe fn add(&mut self) {
281         if self.added { return }
282         let selector = &mut *self.selector;
283         let me = self as *mut Handle<'rx, T> as *mut Handle<'static, ()>;
284
285         if selector.head.is_null() {
286             selector.head = me;
287             selector.tail = me;
288         } else {
289             (*me).prev = selector.tail;
290             assert!((*me).next.is_null());
291             (*selector.tail).next = me;
292             selector.tail = me;
293         }
294         self.added = true;
295     }
296
297     /// Removes this handle from the `Select` set. This method is unsafe because
298     /// it has no guarantee that the `Handle` was not moved since `add` was
299     /// called.
300     pub unsafe fn remove(&mut self) {
301         if !self.added { return }
302
303         let selector = &mut *self.selector;
304         let me = self as *mut Handle<'rx, T> as *mut Handle<'static, ()>;
305
306         if self.prev.is_null() {
307             assert_eq!(selector.head, me);
308             selector.head = self.next;
309         } else {
310             (*self.prev).next = self.next;
311         }
312         if self.next.is_null() {
313             assert_eq!(selector.tail, me);
314             selector.tail = self.prev;
315         } else {
316             (*self.next).prev = self.prev;
317         }
318
319         self.next = ptr::null_mut();
320         self.prev = ptr::null_mut();
321
322         self.added = false;
323     }
324 }
325
326 impl Drop for Select {
327     fn drop(&mut self) {
328         unsafe {
329             assert!((&*self.inner.get()).head.is_null());
330             assert!((&*self.inner.get()).tail.is_null());
331         }
332     }
333 }
334
335 impl<'rx, T: Send> Drop for Handle<'rx, T> {
336     fn drop(&mut self) {
337         unsafe { self.remove() }
338     }
339 }
340
341 impl Iterator for Packets {
342     type Item = *mut Handle<'static, ()>;
343
344     fn next(&mut self) -> Option<*mut Handle<'static, ()>> {
345         if self.cur.is_null() {
346             None
347         } else {
348             let ret = Some(self.cur);
349             unsafe { self.cur = (*self.cur).next; }
350             ret
351         }
352     }
353 }
354
355 impl fmt::Debug for Select {
356     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357         write!(f, "Select {{ .. }}")
358     }
359 }
360
361 impl<'rx, T:Send+'rx> fmt::Debug for Handle<'rx, T> {
362     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
363         write!(f, "Handle {{ .. }}")
364     }
365 }
366
367 #[allow(unused_imports)]
368 #[cfg(all(test, not(target_os = "emscripten")))]
369 mod tests {
370     use thread;
371     use sync::mpsc::*;
372
373     // Don't use the libstd version so we can pull in the right Select structure
374     // (std::comm points at the wrong one)
375     macro_rules! select {
376         (
377             $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
378         ) => ({
379             let sel = Select::new();
380             $( let mut $rx = sel.handle(&$rx); )+
381             unsafe {
382                 $( $rx.add(); )+
383             }
384             let ret = sel.wait();
385             $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
386             { unreachable!() }
387         })
388     }
389
390     #[test]
391     fn smoke() {
392         let (tx1, rx1) = channel::<i32>();
393         let (tx2, rx2) = channel::<i32>();
394         tx1.send(1).unwrap();
395         select! {
396             foo = rx1.recv() => { assert_eq!(foo.unwrap(), 1); },
397             _bar = rx2.recv() => { panic!() }
398         }
399         tx2.send(2).unwrap();
400         select! {
401             _foo = rx1.recv() => { panic!() },
402             bar = rx2.recv() => { assert_eq!(bar.unwrap(), 2) }
403         }
404         drop(tx1);
405         select! {
406             foo = rx1.recv() => { assert!(foo.is_err()); },
407             _bar = rx2.recv() => { panic!() }
408         }
409         drop(tx2);
410         select! {
411             bar = rx2.recv() => { assert!(bar.is_err()); }
412         }
413     }
414
415     #[test]
416     fn smoke2() {
417         let (_tx1, rx1) = channel::<i32>();
418         let (_tx2, rx2) = channel::<i32>();
419         let (_tx3, rx3) = channel::<i32>();
420         let (_tx4, rx4) = channel::<i32>();
421         let (tx5, rx5) = channel::<i32>();
422         tx5.send(4).unwrap();
423         select! {
424             _foo = rx1.recv() => { panic!("1") },
425             _foo = rx2.recv() => { panic!("2") },
426             _foo = rx3.recv() => { panic!("3") },
427             _foo = rx4.recv() => { panic!("4") },
428             foo = rx5.recv() => { assert_eq!(foo.unwrap(), 4); }
429         }
430     }
431
432     #[test]
433     fn closed() {
434         let (_tx1, rx1) = channel::<i32>();
435         let (tx2, rx2) = channel::<i32>();
436         drop(tx2);
437
438         select! {
439             _a1 = rx1.recv() => { panic!() },
440             a2 = rx2.recv() => { assert!(a2.is_err()); }
441         }
442     }
443
444     #[test]
445     fn unblocks() {
446         let (tx1, rx1) = channel::<i32>();
447         let (_tx2, rx2) = channel::<i32>();
448         let (tx3, rx3) = channel::<i32>();
449
450         let _t = thread::spawn(move|| {
451             for _ in 0..20 { thread::yield_now(); }
452             tx1.send(1).unwrap();
453             rx3.recv().unwrap();
454             for _ in 0..20 { thread::yield_now(); }
455         });
456
457         select! {
458             a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
459             _b = rx2.recv() => { panic!() }
460         }
461         tx3.send(1).unwrap();
462         select! {
463             a = rx1.recv() => { assert!(a.is_err()) },
464             _b = rx2.recv() => { panic!() }
465         }
466     }
467
468     #[test]
469     fn both_ready() {
470         let (tx1, rx1) = channel::<i32>();
471         let (tx2, rx2) = channel::<i32>();
472         let (tx3, rx3) = channel::<()>();
473
474         let _t = thread::spawn(move|| {
475             for _ in 0..20 { thread::yield_now(); }
476             tx1.send(1).unwrap();
477             tx2.send(2).unwrap();
478             rx3.recv().unwrap();
479         });
480
481         select! {
482             a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
483             a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
484         }
485         select! {
486             a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
487             a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
488         }
489         assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
490         assert_eq!(rx2.try_recv(), Err(TryRecvError::Empty));
491         tx3.send(()).unwrap();
492     }
493
494     #[test]
495     fn stress() {
496         const AMT: i32 = 10000;
497         let (tx1, rx1) = channel::<i32>();
498         let (tx2, rx2) = channel::<i32>();
499         let (tx3, rx3) = channel::<()>();
500
501         let _t = thread::spawn(move|| {
502             for i in 0..AMT {
503                 if i % 2 == 0 {
504                     tx1.send(i).unwrap();
505                 } else {
506                     tx2.send(i).unwrap();
507                 }
508                 rx3.recv().unwrap();
509             }
510         });
511
512         for i in 0..AMT {
513             select! {
514                 i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1.unwrap()); },
515                 i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2.unwrap()); }
516             }
517             tx3.send(()).unwrap();
518         }
519     }
520
521     #[test]
522     fn cloning() {
523         let (tx1, rx1) = channel::<i32>();
524         let (_tx2, rx2) = channel::<i32>();
525         let (tx3, rx3) = channel::<()>();
526
527         let _t = thread::spawn(move|| {
528             rx3.recv().unwrap();
529             tx1.clone();
530             assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
531             tx1.send(2).unwrap();
532             rx3.recv().unwrap();
533         });
534
535         tx3.send(()).unwrap();
536         select! {
537             _i1 = rx1.recv() => {},
538             _i2 = rx2.recv() => panic!()
539         }
540         tx3.send(()).unwrap();
541     }
542
543     #[test]
544     fn cloning2() {
545         let (tx1, rx1) = channel::<i32>();
546         let (_tx2, rx2) = channel::<i32>();
547         let (tx3, rx3) = channel::<()>();
548
549         let _t = thread::spawn(move|| {
550             rx3.recv().unwrap();
551             tx1.clone();
552             assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
553             tx1.send(2).unwrap();
554             rx3.recv().unwrap();
555         });
556
557         tx3.send(()).unwrap();
558         select! {
559             _i1 = rx1.recv() => {},
560             _i2 = rx2.recv() => panic!()
561         }
562         tx3.send(()).unwrap();
563     }
564
565     #[test]
566     fn cloning3() {
567         let (tx1, rx1) = channel::<()>();
568         let (tx2, rx2) = channel::<()>();
569         let (tx3, rx3) = channel::<()>();
570         let _t = thread::spawn(move|| {
571             let s = Select::new();
572             let mut h1 = s.handle(&rx1);
573             let mut h2 = s.handle(&rx2);
574             unsafe { h2.add(); }
575             unsafe { h1.add(); }
576             assert_eq!(s.wait(), h2.id);
577             tx3.send(()).unwrap();
578         });
579
580         for _ in 0..1000 { thread::yield_now(); }
581         drop(tx1.clone());
582         tx2.send(()).unwrap();
583         rx3.recv().unwrap();
584     }
585
586     #[test]
587     fn preflight1() {
588         let (tx, rx) = channel();
589         tx.send(()).unwrap();
590         select! {
591             _n = rx.recv() => {}
592         }
593     }
594
595     #[test]
596     fn preflight2() {
597         let (tx, rx) = channel();
598         tx.send(()).unwrap();
599         tx.send(()).unwrap();
600         select! {
601             _n = rx.recv() => {}
602         }
603     }
604
605     #[test]
606     fn preflight3() {
607         let (tx, rx) = channel();
608         drop(tx.clone());
609         tx.send(()).unwrap();
610         select! {
611             _n = rx.recv() => {}
612         }
613     }
614
615     #[test]
616     fn preflight4() {
617         let (tx, rx) = channel();
618         tx.send(()).unwrap();
619         let s = Select::new();
620         let mut h = s.handle(&rx);
621         unsafe { h.add(); }
622         assert_eq!(s.wait2(false), h.id);
623     }
624
625     #[test]
626     fn preflight5() {
627         let (tx, rx) = channel();
628         tx.send(()).unwrap();
629         tx.send(()).unwrap();
630         let s = Select::new();
631         let mut h = s.handle(&rx);
632         unsafe { h.add(); }
633         assert_eq!(s.wait2(false), h.id);
634     }
635
636     #[test]
637     fn preflight6() {
638         let (tx, rx) = channel();
639         drop(tx.clone());
640         tx.send(()).unwrap();
641         let s = Select::new();
642         let mut h = s.handle(&rx);
643         unsafe { h.add(); }
644         assert_eq!(s.wait2(false), h.id);
645     }
646
647     #[test]
648     fn preflight7() {
649         let (tx, rx) = channel::<()>();
650         drop(tx);
651         let s = Select::new();
652         let mut h = s.handle(&rx);
653         unsafe { h.add(); }
654         assert_eq!(s.wait2(false), h.id);
655     }
656
657     #[test]
658     fn preflight8() {
659         let (tx, rx) = channel();
660         tx.send(()).unwrap();
661         drop(tx);
662         rx.recv().unwrap();
663         let s = Select::new();
664         let mut h = s.handle(&rx);
665         unsafe { h.add(); }
666         assert_eq!(s.wait2(false), h.id);
667     }
668
669     #[test]
670     fn preflight9() {
671         let (tx, rx) = channel();
672         drop(tx.clone());
673         tx.send(()).unwrap();
674         drop(tx);
675         rx.recv().unwrap();
676         let s = Select::new();
677         let mut h = s.handle(&rx);
678         unsafe { h.add(); }
679         assert_eq!(s.wait2(false), h.id);
680     }
681
682     #[test]
683     fn oneshot_data_waiting() {
684         let (tx1, rx1) = channel();
685         let (tx2, rx2) = channel();
686         let _t = thread::spawn(move|| {
687             select! {
688                 _n = rx1.recv() => {}
689             }
690             tx2.send(()).unwrap();
691         });
692
693         for _ in 0..100 { thread::yield_now() }
694         tx1.send(()).unwrap();
695         rx2.recv().unwrap();
696     }
697
698     #[test]
699     fn stream_data_waiting() {
700         let (tx1, rx1) = channel();
701         let (tx2, rx2) = channel();
702         tx1.send(()).unwrap();
703         tx1.send(()).unwrap();
704         rx1.recv().unwrap();
705         rx1.recv().unwrap();
706         let _t = thread::spawn(move|| {
707             select! {
708                 _n = rx1.recv() => {}
709             }
710             tx2.send(()).unwrap();
711         });
712
713         for _ in 0..100 { thread::yield_now() }
714         tx1.send(()).unwrap();
715         rx2.recv().unwrap();
716     }
717
718     #[test]
719     fn shared_data_waiting() {
720         let (tx1, rx1) = channel();
721         let (tx2, rx2) = channel();
722         drop(tx1.clone());
723         tx1.send(()).unwrap();
724         rx1.recv().unwrap();
725         let _t = thread::spawn(move|| {
726             select! {
727                 _n = rx1.recv() => {}
728             }
729             tx2.send(()).unwrap();
730         });
731
732         for _ in 0..100 { thread::yield_now() }
733         tx1.send(()).unwrap();
734         rx2.recv().unwrap();
735     }
736
737     #[test]
738     fn sync1() {
739         let (tx, rx) = sync_channel::<i32>(1);
740         tx.send(1).unwrap();
741         select! {
742             n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
743         }
744     }
745
746     #[test]
747     fn sync2() {
748         let (tx, rx) = sync_channel::<i32>(0);
749         let _t = thread::spawn(move|| {
750             for _ in 0..100 { thread::yield_now() }
751             tx.send(1).unwrap();
752         });
753         select! {
754             n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
755         }
756     }
757
758     #[test]
759     fn sync3() {
760         let (tx1, rx1) = sync_channel::<i32>(0);
761         let (tx2, rx2): (Sender<i32>, Receiver<i32>) = channel();
762         let _t = thread::spawn(move|| { tx1.send(1).unwrap(); });
763         let _t = thread::spawn(move|| { tx2.send(2).unwrap(); });
764         select! {
765             n = rx1.recv() => {
766                 let n = n.unwrap();
767                 assert_eq!(n, 1);
768                 assert_eq!(rx2.recv().unwrap(), 2);
769             },
770             n = rx2.recv() => {
771                 let n = n.unwrap();
772                 assert_eq!(n, 2);
773                 assert_eq!(rx1.recv().unwrap(), 1);
774             }
775         }
776     }
777
778     #[test]
779     fn fmt_debug_select() {
780         let sel = Select::new();
781         assert_eq!(format!("{:?}", sel), "Select { .. }");
782     }
783
784     #[test]
785     fn fmt_debug_handle() {
786         let (_, rx) = channel::<i32>();
787         let sel = Select::new();
788         let handle = sel.handle(&rx);
789         assert_eq!(format!("{:?}", handle), "Handle { .. }");
790     }
791 }