]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mpsc/select.rs
Changed issue number to 36105
[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)]
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 #[stable(feature = "mpsc_debug", since = "1.7.0")]
356 impl fmt::Debug for Select {
357     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
358         write!(f, "Select {{ .. }}")
359     }
360 }
361
362 #[stable(feature = "mpsc_debug", since = "1.7.0")]
363 impl<'rx, T:Send+'rx> fmt::Debug for Handle<'rx, T> {
364     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
365         write!(f, "Handle {{ .. }}")
366     }
367 }
368
369 #[cfg(test)]
370 #[allow(unused_imports)]
371 mod tests {
372     use prelude::v1::*;
373
374     use thread;
375     use sync::mpsc::*;
376
377     // Don't use the libstd version so we can pull in the right Select structure
378     // (std::comm points at the wrong one)
379     macro_rules! select {
380         (
381             $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
382         ) => ({
383             let sel = Select::new();
384             $( let mut $rx = sel.handle(&$rx); )+
385             unsafe {
386                 $( $rx.add(); )+
387             }
388             let ret = sel.wait();
389             $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
390             { unreachable!() }
391         })
392     }
393
394     #[test]
395     fn smoke() {
396         let (tx1, rx1) = channel::<i32>();
397         let (tx2, rx2) = channel::<i32>();
398         tx1.send(1).unwrap();
399         select! {
400             foo = rx1.recv() => { assert_eq!(foo.unwrap(), 1); },
401             _bar = rx2.recv() => { panic!() }
402         }
403         tx2.send(2).unwrap();
404         select! {
405             _foo = rx1.recv() => { panic!() },
406             bar = rx2.recv() => { assert_eq!(bar.unwrap(), 2) }
407         }
408         drop(tx1);
409         select! {
410             foo = rx1.recv() => { assert!(foo.is_err()); },
411             _bar = rx2.recv() => { panic!() }
412         }
413         drop(tx2);
414         select! {
415             bar = rx2.recv() => { assert!(bar.is_err()); }
416         }
417     }
418
419     #[test]
420     fn smoke2() {
421         let (_tx1, rx1) = channel::<i32>();
422         let (_tx2, rx2) = channel::<i32>();
423         let (_tx3, rx3) = channel::<i32>();
424         let (_tx4, rx4) = channel::<i32>();
425         let (tx5, rx5) = channel::<i32>();
426         tx5.send(4).unwrap();
427         select! {
428             _foo = rx1.recv() => { panic!("1") },
429             _foo = rx2.recv() => { panic!("2") },
430             _foo = rx3.recv() => { panic!("3") },
431             _foo = rx4.recv() => { panic!("4") },
432             foo = rx5.recv() => { assert_eq!(foo.unwrap(), 4); }
433         }
434     }
435
436     #[test]
437     fn closed() {
438         let (_tx1, rx1) = channel::<i32>();
439         let (tx2, rx2) = channel::<i32>();
440         drop(tx2);
441
442         select! {
443             _a1 = rx1.recv() => { panic!() },
444             a2 = rx2.recv() => { assert!(a2.is_err()); }
445         }
446     }
447
448     #[test]
449     fn unblocks() {
450         let (tx1, rx1) = channel::<i32>();
451         let (_tx2, rx2) = channel::<i32>();
452         let (tx3, rx3) = channel::<i32>();
453
454         let _t = thread::spawn(move|| {
455             for _ in 0..20 { thread::yield_now(); }
456             tx1.send(1).unwrap();
457             rx3.recv().unwrap();
458             for _ in 0..20 { thread::yield_now(); }
459         });
460
461         select! {
462             a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
463             _b = rx2.recv() => { panic!() }
464         }
465         tx3.send(1).unwrap();
466         select! {
467             a = rx1.recv() => { assert!(a.is_err()) },
468             _b = rx2.recv() => { panic!() }
469         }
470     }
471
472     #[test]
473     fn both_ready() {
474         let (tx1, rx1) = channel::<i32>();
475         let (tx2, rx2) = channel::<i32>();
476         let (tx3, rx3) = channel::<()>();
477
478         let _t = thread::spawn(move|| {
479             for _ in 0..20 { thread::yield_now(); }
480             tx1.send(1).unwrap();
481             tx2.send(2).unwrap();
482             rx3.recv().unwrap();
483         });
484
485         select! {
486             a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
487             a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
488         }
489         select! {
490             a = rx1.recv() => { assert_eq!(a.unwrap(), 1); },
491             a = rx2.recv() => { assert_eq!(a.unwrap(), 2); }
492         }
493         assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
494         assert_eq!(rx2.try_recv(), Err(TryRecvError::Empty));
495         tx3.send(()).unwrap();
496     }
497
498     #[test]
499     fn stress() {
500         const AMT: i32 = 10000;
501         let (tx1, rx1) = channel::<i32>();
502         let (tx2, rx2) = channel::<i32>();
503         let (tx3, rx3) = channel::<()>();
504
505         let _t = thread::spawn(move|| {
506             for i in 0..AMT {
507                 if i % 2 == 0 {
508                     tx1.send(i).unwrap();
509                 } else {
510                     tx2.send(i).unwrap();
511                 }
512                 rx3.recv().unwrap();
513             }
514         });
515
516         for i in 0..AMT {
517             select! {
518                 i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1.unwrap()); },
519                 i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2.unwrap()); }
520             }
521             tx3.send(()).unwrap();
522         }
523     }
524
525     #[test]
526     fn cloning() {
527         let (tx1, rx1) = channel::<i32>();
528         let (_tx2, rx2) = channel::<i32>();
529         let (tx3, rx3) = channel::<()>();
530
531         let _t = thread::spawn(move|| {
532             rx3.recv().unwrap();
533             tx1.clone();
534             assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
535             tx1.send(2).unwrap();
536             rx3.recv().unwrap();
537         });
538
539         tx3.send(()).unwrap();
540         select! {
541             _i1 = rx1.recv() => {},
542             _i2 = rx2.recv() => panic!()
543         }
544         tx3.send(()).unwrap();
545     }
546
547     #[test]
548     fn cloning2() {
549         let (tx1, rx1) = channel::<i32>();
550         let (_tx2, rx2) = channel::<i32>();
551         let (tx3, rx3) = channel::<()>();
552
553         let _t = thread::spawn(move|| {
554             rx3.recv().unwrap();
555             tx1.clone();
556             assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty));
557             tx1.send(2).unwrap();
558             rx3.recv().unwrap();
559         });
560
561         tx3.send(()).unwrap();
562         select! {
563             _i1 = rx1.recv() => {},
564             _i2 = rx2.recv() => panic!()
565         }
566         tx3.send(()).unwrap();
567     }
568
569     #[test]
570     fn cloning3() {
571         let (tx1, rx1) = channel::<()>();
572         let (tx2, rx2) = channel::<()>();
573         let (tx3, rx3) = channel::<()>();
574         let _t = thread::spawn(move|| {
575             let s = Select::new();
576             let mut h1 = s.handle(&rx1);
577             let mut h2 = s.handle(&rx2);
578             unsafe { h2.add(); }
579             unsafe { h1.add(); }
580             assert_eq!(s.wait(), h2.id);
581             tx3.send(()).unwrap();
582         });
583
584         for _ in 0..1000 { thread::yield_now(); }
585         drop(tx1.clone());
586         tx2.send(()).unwrap();
587         rx3.recv().unwrap();
588     }
589
590     #[test]
591     fn preflight1() {
592         let (tx, rx) = channel();
593         tx.send(()).unwrap();
594         select! {
595             _n = rx.recv() => {}
596         }
597     }
598
599     #[test]
600     fn preflight2() {
601         let (tx, rx) = channel();
602         tx.send(()).unwrap();
603         tx.send(()).unwrap();
604         select! {
605             _n = rx.recv() => {}
606         }
607     }
608
609     #[test]
610     fn preflight3() {
611         let (tx, rx) = channel();
612         drop(tx.clone());
613         tx.send(()).unwrap();
614         select! {
615             _n = rx.recv() => {}
616         }
617     }
618
619     #[test]
620     fn preflight4() {
621         let (tx, rx) = channel();
622         tx.send(()).unwrap();
623         let s = Select::new();
624         let mut h = s.handle(&rx);
625         unsafe { h.add(); }
626         assert_eq!(s.wait2(false), h.id);
627     }
628
629     #[test]
630     fn preflight5() {
631         let (tx, rx) = channel();
632         tx.send(()).unwrap();
633         tx.send(()).unwrap();
634         let s = Select::new();
635         let mut h = s.handle(&rx);
636         unsafe { h.add(); }
637         assert_eq!(s.wait2(false), h.id);
638     }
639
640     #[test]
641     fn preflight6() {
642         let (tx, rx) = channel();
643         drop(tx.clone());
644         tx.send(()).unwrap();
645         let s = Select::new();
646         let mut h = s.handle(&rx);
647         unsafe { h.add(); }
648         assert_eq!(s.wait2(false), h.id);
649     }
650
651     #[test]
652     fn preflight7() {
653         let (tx, rx) = channel::<()>();
654         drop(tx);
655         let s = Select::new();
656         let mut h = s.handle(&rx);
657         unsafe { h.add(); }
658         assert_eq!(s.wait2(false), h.id);
659     }
660
661     #[test]
662     fn preflight8() {
663         let (tx, rx) = channel();
664         tx.send(()).unwrap();
665         drop(tx);
666         rx.recv().unwrap();
667         let s = Select::new();
668         let mut h = s.handle(&rx);
669         unsafe { h.add(); }
670         assert_eq!(s.wait2(false), h.id);
671     }
672
673     #[test]
674     fn preflight9() {
675         let (tx, rx) = channel();
676         drop(tx.clone());
677         tx.send(()).unwrap();
678         drop(tx);
679         rx.recv().unwrap();
680         let s = Select::new();
681         let mut h = s.handle(&rx);
682         unsafe { h.add(); }
683         assert_eq!(s.wait2(false), h.id);
684     }
685
686     #[test]
687     fn oneshot_data_waiting() {
688         let (tx1, rx1) = channel();
689         let (tx2, rx2) = channel();
690         let _t = thread::spawn(move|| {
691             select! {
692                 _n = rx1.recv() => {}
693             }
694             tx2.send(()).unwrap();
695         });
696
697         for _ in 0..100 { thread::yield_now() }
698         tx1.send(()).unwrap();
699         rx2.recv().unwrap();
700     }
701
702     #[test]
703     fn stream_data_waiting() {
704         let (tx1, rx1) = channel();
705         let (tx2, rx2) = channel();
706         tx1.send(()).unwrap();
707         tx1.send(()).unwrap();
708         rx1.recv().unwrap();
709         rx1.recv().unwrap();
710         let _t = thread::spawn(move|| {
711             select! {
712                 _n = rx1.recv() => {}
713             }
714             tx2.send(()).unwrap();
715         });
716
717         for _ in 0..100 { thread::yield_now() }
718         tx1.send(()).unwrap();
719         rx2.recv().unwrap();
720     }
721
722     #[test]
723     fn shared_data_waiting() {
724         let (tx1, rx1) = channel();
725         let (tx2, rx2) = channel();
726         drop(tx1.clone());
727         tx1.send(()).unwrap();
728         rx1.recv().unwrap();
729         let _t = thread::spawn(move|| {
730             select! {
731                 _n = rx1.recv() => {}
732             }
733             tx2.send(()).unwrap();
734         });
735
736         for _ in 0..100 { thread::yield_now() }
737         tx1.send(()).unwrap();
738         rx2.recv().unwrap();
739     }
740
741     #[test]
742     fn sync1() {
743         let (tx, rx) = sync_channel::<i32>(1);
744         tx.send(1).unwrap();
745         select! {
746             n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
747         }
748     }
749
750     #[test]
751     fn sync2() {
752         let (tx, rx) = sync_channel::<i32>(0);
753         let _t = thread::spawn(move|| {
754             for _ in 0..100 { thread::yield_now() }
755             tx.send(1).unwrap();
756         });
757         select! {
758             n = rx.recv() => { assert_eq!(n.unwrap(), 1); }
759         }
760     }
761
762     #[test]
763     fn sync3() {
764         let (tx1, rx1) = sync_channel::<i32>(0);
765         let (tx2, rx2): (Sender<i32>, Receiver<i32>) = channel();
766         let _t = thread::spawn(move|| { tx1.send(1).unwrap(); });
767         let _t = thread::spawn(move|| { tx2.send(2).unwrap(); });
768         select! {
769             n = rx1.recv() => {
770                 let n = n.unwrap();
771                 assert_eq!(n, 1);
772                 assert_eq!(rx2.recv().unwrap(), 2);
773             },
774             n = rx2.recv() => {
775                 let n = n.unwrap();
776                 assert_eq!(n, 2);
777                 assert_eq!(rx1.recv().unwrap(), 1);
778             }
779         }
780     }
781
782     #[test]
783     fn fmt_debug_select() {
784         let sel = Select::new();
785         assert_eq!(format!("{:?}", sel), "Select { .. }");
786     }
787
788     #[test]
789     fn fmt_debug_handle() {
790         let (_, rx) = channel::<i32>();
791         let sel = Select::new();
792         let handle = sel.handle(&rx);
793         assert_eq!(format!("{:?}", handle), "Handle { .. }");
794     }
795 }