]> git.lizzy.rs Git - rust.git/blob - src/libsync/comm/mod.rs
Implement generalized object and type parameter bounds (Fixes #16462)
[rust.git] / src / libsync / comm / mod.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 //! Communication primitives for concurrent tasks
12 //!
13 //! Rust makes it very difficult to share data among tasks to prevent race
14 //! conditions and to improve parallelism, but there is often a need for
15 //! communication between concurrent tasks. The primitives defined in this
16 //! module are the building blocks for synchronization in rust.
17 //!
18 //! This module provides message-based communication over channels, concretely
19 //! defined among three types:
20 //!
21 //! * `Sender`
22 //! * `SyncSender`
23 //! * `Receiver`
24 //!
25 //! A `Sender` or `SyncSender` is used to send data to a `Receiver`. Both
26 //! senders are clone-able such that many tasks can send simultaneously to one
27 //! receiver.  These channels are *task blocking*, not *thread blocking*. This
28 //! means that if one task is blocked on a channel, other tasks can continue to
29 //! make progress.
30 //!
31 //! Rust channels come in one of two flavors:
32 //!
33 //! 1. An asynchronous, infinitely buffered channel. The `channel()` function
34 //!    will return a `(Sender, Receiver)` tuple where all sends will be
35 //!    **asynchronous** (they never block). The channel conceptually has an
36 //!    infinite buffer.
37 //!
38 //! 2. A synchronous, bounded channel. The `sync_channel()` function will return
39 //!    a `(SyncSender, Receiver)` tuple where the storage for pending messages
40 //!    is a pre-allocated buffer of a fixed size. All sends will be
41 //!    **synchronous** by blocking until there is buffer space available. Note
42 //!    that a bound of 0 is allowed, causing the channel to become a
43 //!    "rendezvous" channel where each sender atomically hands off a message to
44 //!    a receiver.
45 //!
46 //! ## Failure Propagation
47 //!
48 //! In addition to being a core primitive for communicating in rust, channels
49 //! are the points at which failure is propagated among tasks.  Whenever the one
50 //! half of channel is closed, the other half will have its next operation
51 //! `fail!`. The purpose of this is to allow propagation of failure among tasks
52 //! that are linked to one another via channels.
53 //!
54 //! There are methods on both of senders and receivers to perform their
55 //! respective operations without failing, however.
56 //!
57 //! ## Runtime Requirements
58 //!
59 //! The channel types defined in this module generally have very few runtime
60 //! requirements in order to operate. The major requirement they have is for a
61 //! local rust `Task` to be available if any *blocking* operation is performed.
62 //!
63 //! If a local `Task` is not available (for example an FFI callback), then the
64 //! `send` operation is safe on a `Sender` (as well as a `send_opt`) as well as
65 //! the `try_send` method on a `SyncSender`, but no other operations are
66 //! guaranteed to be safe.
67 //!
68 //! Additionally, channels can interoperate between runtimes. If one task in a
69 //! program is running on libnative and another is running on libgreen, they can
70 //! still communicate with one another using channels.
71 //!
72 //! # Example
73 //!
74 //! Simple usage:
75 //!
76 //! ```
77 //! // Create a simple streaming channel
78 //! let (tx, rx) = channel();
79 //! spawn(proc() {
80 //!     tx.send(10i);
81 //! });
82 //! assert_eq!(rx.recv(), 10i);
83 //! ```
84 //!
85 //! Shared usage:
86 //!
87 //! ```
88 //! // Create a shared channel which can be sent along from many tasks
89 //! // where tx is the sending half (tx for transmission), and rx is the receiving
90 //! // half (rx for receiving).
91 //! let (tx, rx) = channel();
92 //! for i in range(0i, 10i) {
93 //!     let tx = tx.clone();
94 //!     spawn(proc() {
95 //!         tx.send(i);
96 //!     })
97 //! }
98 //!
99 //! for _ in range(0i, 10i) {
100 //!     let j = rx.recv();
101 //!     assert!(0 <= j && j < 10);
102 //! }
103 //! ```
104 //!
105 //! Propagating failure:
106 //!
107 //! ```should_fail
108 //! // The call to recv() will fail!() because the channel has already hung
109 //! // up (or been deallocated)
110 //! let (tx, rx) = channel::<int>();
111 //! drop(tx);
112 //! rx.recv();
113 //! ```
114 //!
115 //! Synchronous channels:
116 //!
117 //! ```
118 //! let (tx, rx) = sync_channel::<int>(0);
119 //! spawn(proc() {
120 //!     // This will wait for the parent task to start receiving
121 //!     tx.send(53);
122 //! });
123 //! rx.recv();
124 //! ```
125 //!
126 //! Reading from a channel with a timeout requires to use a Timer together
127 //! with the channel. You can use the select! macro to select either and
128 //! handle the timeout case. This first example will break out of the loop
129 //! after 10 seconds no matter what:
130 //!
131 //! ```no_run
132 //! use std::io::timer::Timer;
133 //! use std::time::Duration;
134 //!
135 //! let (tx, rx) = channel::<int>();
136 //! let mut timer = Timer::new().unwrap();
137 //! let timeout = timer.oneshot(Duration::seconds(10));
138 //!
139 //! loop {
140 //!     select! {
141 //!         val = rx.recv() => println!("Received {}", val),
142 //!         () = timeout.recv() => {
143 //!             println!("timed out, total time was more than 10 seconds")
144 //!             break;
145 //!         }
146 //!     }
147 //! }
148 //! ```
149 //!
150 //! This second example is more costly since it allocates a new timer every
151 //! time a message is received, but it allows you to timeout after the channel
152 //! has been inactive for 5 seconds:
153 //!
154 //! ```no_run
155 //! use std::io::timer::Timer;
156 //! use std::time::Duration;
157 //!
158 //! let (tx, rx) = channel::<int>();
159 //! let mut timer = Timer::new().unwrap();
160 //!
161 //! loop {
162 //!     let timeout = timer.oneshot(Duration::seconds(5));
163 //!
164 //!     select! {
165 //!         val = rx.recv() => println!("Received {}", val),
166 //!         () = timeout.recv() => {
167 //!             println!("timed out, no message received in 5 seconds")
168 //!             break;
169 //!         }
170 //!     }
171 //! }
172 //! ```
173
174 // A description of how Rust's channel implementation works
175 //
176 // Channels are supposed to be the basic building block for all other
177 // concurrent primitives that are used in Rust. As a result, the channel type
178 // needs to be highly optimized, flexible, and broad enough for use everywhere.
179 //
180 // The choice of implementation of all channels is to be built on lock-free data
181 // structures. The channels themselves are then consequently also lock-free data
182 // structures. As always with lock-free code, this is a very "here be dragons"
183 // territory, especially because I'm unaware of any academic papers which have
184 // gone into great length about channels of these flavors.
185 //
186 // ## Flavors of channels
187 //
188 // From the perspective of a consumer of this library, there is only one flavor
189 // of channel. This channel can be used as a stream and cloned to allow multiple
190 // senders. Under the hood, however, there are actually three flavors of
191 // channels in play.
192 //
193 // * Oneshots - these channels are highly optimized for the one-send use case.
194 //              They contain as few atomics as possible and involve one and
195 //              exactly one allocation.
196 // * Streams - these channels are optimized for the non-shared use case. They
197 //             use a different concurrent queue which is more tailored for this
198 //             use case. The initial allocation of this flavor of channel is not
199 //             optimized.
200 // * Shared - this is the most general form of channel that this module offers,
201 //            a channel with multiple senders. This type is as optimized as it
202 //            can be, but the previous two types mentioned are much faster for
203 //            their use-cases.
204 //
205 // ## Concurrent queues
206 //
207 // The basic idea of Rust's Sender/Receiver types is that send() never blocks, but
208 // recv() obviously blocks. This means that under the hood there must be some
209 // shared and concurrent queue holding all of the actual data.
210 //
211 // With two flavors of channels, two flavors of queues are also used. We have
212 // chosen to use queues from a well-known author which are abbreviated as SPSC
213 // and MPSC (single producer, single consumer and multiple producer, single
214 // consumer). SPSC queues are used for streams while MPSC queues are used for
215 // shared channels.
216 //
217 // ### SPSC optimizations
218 //
219 // The SPSC queue found online is essentially a linked list of nodes where one
220 // half of the nodes are the "queue of data" and the other half of nodes are a
221 // cache of unused nodes. The unused nodes are used such that an allocation is
222 // not required on every push() and a free doesn't need to happen on every
223 // pop().
224 //
225 // As found online, however, the cache of nodes is of an infinite size. This
226 // means that if a channel at one point in its life had 50k items in the queue,
227 // then the queue will always have the capacity for 50k items. I believed that
228 // this was an unnecessary limitation of the implementation, so I have altered
229 // the queue to optionally have a bound on the cache size.
230 //
231 // By default, streams will have an unbounded SPSC queue with a small-ish cache
232 // size. The hope is that the cache is still large enough to have very fast
233 // send() operations while not too large such that millions of channels can
234 // coexist at once.
235 //
236 // ### MPSC optimizations
237 //
238 // Right now the MPSC queue has not been optimized. Like the SPSC queue, it uses
239 // a linked list under the hood to earn its unboundedness, but I have not put
240 // forth much effort into having a cache of nodes similar to the SPSC queue.
241 //
242 // For now, I believe that this is "ok" because shared channels are not the most
243 // common type, but soon we may wish to revisit this queue choice and determine
244 // another candidate for backend storage of shared channels.
245 //
246 // ## Overview of the Implementation
247 //
248 // Now that there's a little background on the concurrent queues used, it's
249 // worth going into much more detail about the channels themselves. The basic
250 // pseudocode for a send/recv are:
251 //
252 //
253 //      send(t)                             recv()
254 //        queue.push(t)                       return if queue.pop()
255 //        if increment() == -1                deschedule {
256 //          wakeup()                            if decrement() > 0
257 //                                                cancel_deschedule()
258 //                                            }
259 //                                            queue.pop()
260 //
261 // As mentioned before, there are no locks in this implementation, only atomic
262 // instructions are used.
263 //
264 // ### The internal atomic counter
265 //
266 // Every channel has a shared counter with each half to keep track of the size
267 // of the queue. This counter is used to abort descheduling by the receiver and
268 // to know when to wake up on the sending side.
269 //
270 // As seen in the pseudocode, senders will increment this count and receivers
271 // will decrement the count. The theory behind this is that if a sender sees a
272 // -1 count, it will wake up the receiver, and if the receiver sees a 1+ count,
273 // then it doesn't need to block.
274 //
275 // The recv() method has a beginning call to pop(), and if successful, it needs
276 // to decrement the count. It is a crucial implementation detail that this
277 // decrement does *not* happen to the shared counter. If this were the case,
278 // then it would be possible for the counter to be very negative when there were
279 // no receivers waiting, in which case the senders would have to determine when
280 // it was actually appropriate to wake up a receiver.
281 //
282 // Instead, the "steal count" is kept track of separately (not atomically
283 // because it's only used by receivers), and then the decrement() call when
284 // descheduling will lump in all of the recent steals into one large decrement.
285 //
286 // The implication of this is that if a sender sees a -1 count, then there's
287 // guaranteed to be a waiter waiting!
288 //
289 // ## Native Implementation
290 //
291 // A major goal of these channels is to work seamlessly on and off the runtime.
292 // All of the previous race conditions have been worded in terms of
293 // scheduler-isms (which is obviously not available without the runtime).
294 //
295 // For now, native usage of channels (off the runtime) will fall back onto
296 // mutexes/cond vars for descheduling/atomic decisions. The no-contention path
297 // is still entirely lock-free, the "deschedule" blocks above are surrounded by
298 // a mutex and the "wakeup" blocks involve grabbing a mutex and signaling on a
299 // condition variable.
300 //
301 // ## Select
302 //
303 // Being able to support selection over channels has greatly influenced this
304 // design, and not only does selection need to work inside the runtime, but also
305 // outside the runtime.
306 //
307 // The implementation is fairly straightforward. The goal of select() is not to
308 // return some data, but only to return which channel can receive data without
309 // blocking. The implementation is essentially the entire blocking procedure
310 // followed by an increment as soon as its woken up. The cancellation procedure
311 // involves an increment and swapping out of to_wake to acquire ownership of the
312 // task to unblock.
313 //
314 // Sadly this current implementation requires multiple allocations, so I have
315 // seen the throughput of select() be much worse than it should be. I do not
316 // believe that there is anything fundamental which needs to change about these
317 // channels, however, in order to support a more efficient select().
318 //
319 // # Conclusion
320 //
321 // And now that you've seen all the races that I found and attempted to fix,
322 // here's the code for you to find some more!
323
324 use core::prelude::*;
325
326 use alloc::arc::Arc;
327 use alloc::boxed::Box;
328 use core::cell::Cell;
329 use core::kinds::marker;
330 use core::mem;
331 use core::cell::UnsafeCell;
332 use rustrt::local::Local;
333 use rustrt::task::{Task, BlockedTask};
334
335 pub use comm::select::{Select, Handle};
336 pub use comm::duplex::{DuplexStream, duplex};
337
338 macro_rules! test (
339     { fn $name:ident() $b:block $(#[$a:meta])*} => (
340         mod $name {
341             #![allow(unused_imports)]
342
343             use std::prelude::*;
344
345             use native;
346             use comm::*;
347             use super::*;
348             use super::super::*;
349             use std::task;
350
351             fn f() $b
352
353             $(#[$a])* #[test] fn uv() { f() }
354             $(#[$a])* #[test] fn native() {
355                 use native;
356                 let (tx, rx) = channel();
357                 native::task::spawn(proc() { tx.send(f()) });
358                 rx.recv();
359             }
360         }
361     )
362 )
363
364 mod duplex;
365 mod oneshot;
366 mod select;
367 mod shared;
368 mod stream;
369 mod sync;
370
371 // Use a power of 2 to allow LLVM to optimize to something that's not a
372 // division, this is hit pretty regularly.
373 static RESCHED_FREQ: int = 256;
374
375 /// The receiving-half of Rust's channel type. This half can only be owned by
376 /// one task
377 #[unstable]
378 pub struct Receiver<T> {
379     inner: UnsafeCell<Flavor<T>>,
380     receives: Cell<uint>,
381     // can't share in an arc
382     marker: marker::NoSync,
383 }
384
385 /// An iterator over messages on a receiver, this iterator will block
386 /// whenever `next` is called, waiting for a new message, and `None` will be
387 /// returned when the corresponding channel has hung up.
388 #[unstable]
389 #[cfg(not(stage0))]
390 pub struct Messages<'a, T:'a> {
391     rx: &'a Receiver<T>
392 }
393
394 /// Stage0 only
395 #[cfg(stage0)]
396 #[unstable]
397 pub struct Messages<'a, T> {
398     rx: &'a Receiver<T>
399 }
400
401 /// The sending-half of Rust's asynchronous channel type. This half can only be
402 /// owned by one task, but it can be cloned to send to other tasks.
403 #[unstable]
404 pub struct Sender<T> {
405     inner: UnsafeCell<Flavor<T>>,
406     sends: Cell<uint>,
407     // can't share in an arc
408     marker: marker::NoSync,
409 }
410
411 /// The sending-half of Rust's synchronous channel type. This half can only be
412 /// owned by one task, but it can be cloned to send to other tasks.
413 #[unstable = "this type may be renamed, but it will always exist"]
414 pub struct SyncSender<T> {
415     inner: Arc<UnsafeCell<sync::Packet<T>>>,
416     // can't share in an arc
417     marker: marker::NoSync,
418 }
419
420 /// This enumeration is the list of the possible reasons that try_recv could not
421 /// return data when called.
422 #[deriving(PartialEq, Clone, Show)]
423 #[experimental = "this is likely to be removed in changing try_recv()"]
424 pub enum TryRecvError {
425     /// This channel is currently empty, but the sender(s) have not yet
426     /// disconnected, so data may yet become available.
427     Empty,
428     /// This channel's sending half has become disconnected, and there will
429     /// never be any more data received on this channel
430     Disconnected,
431 }
432
433 /// This enumeration is the list of the possible error outcomes for the
434 /// `SyncSender::try_send` method.
435 #[deriving(PartialEq, Clone, Show)]
436 #[experimental = "this is likely to be removed in changing try_send()"]
437 pub enum TrySendError<T> {
438     /// The data could not be sent on the channel because it would require that
439     /// the callee block to send the data.
440     ///
441     /// If this is a buffered channel, then the buffer is full at this time. If
442     /// this is not a buffered channel, then there is no receiver available to
443     /// acquire the data.
444     Full(T),
445     /// This channel's receiving half has disconnected, so the data could not be
446     /// sent. The data is returned back to the callee in this case.
447     RecvDisconnected(T),
448 }
449
450 enum Flavor<T> {
451     Oneshot(Arc<UnsafeCell<oneshot::Packet<T>>>),
452     Stream(Arc<UnsafeCell<stream::Packet<T>>>),
453     Shared(Arc<UnsafeCell<shared::Packet<T>>>),
454     Sync(Arc<UnsafeCell<sync::Packet<T>>>),
455 }
456
457 #[doc(hidden)]
458 trait UnsafeFlavor<T> {
459     fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>>;
460     unsafe fn mut_inner<'a>(&'a self) -> &'a mut Flavor<T> {
461         &mut *self.inner_unsafe().get()
462     }
463     unsafe fn inner<'a>(&'a self) -> &'a Flavor<T> {
464         &*self.inner_unsafe().get()
465     }
466 }
467 impl<T> UnsafeFlavor<T> for Sender<T> {
468     fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> {
469         &self.inner
470     }
471 }
472 impl<T> UnsafeFlavor<T> for Receiver<T> {
473     fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> {
474         &self.inner
475     }
476 }
477
478 /// Creates a new asynchronous channel, returning the sender/receiver halves.
479 ///
480 /// All data sent on the sender will become available on the receiver, and no
481 /// send will block the calling task (this channel has an "infinite buffer").
482 ///
483 /// # Example
484 ///
485 /// ```
486 /// // tx is is the sending half (tx for transmission), and rx is the receiving
487 /// // half (rx for receiving).
488 /// let (tx, rx) = channel();
489 ///
490 /// // Spawn off an expensive computation
491 /// spawn(proc() {
492 /// #   fn expensive_computation() {}
493 ///     tx.send(expensive_computation());
494 /// });
495 ///
496 /// // Do some useful work for awhile
497 ///
498 /// // Let's see what that answer was
499 /// println!("{}", rx.recv());
500 /// ```
501 #[unstable]
502 pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) {
503     let a = Arc::new(UnsafeCell::new(oneshot::Packet::new()));
504     (Sender::new(Oneshot(a.clone())), Receiver::new(Oneshot(a)))
505 }
506
507 /// Creates a new synchronous, bounded channel.
508 ///
509 /// Like asynchronous channels, the `Receiver` will block until a message
510 /// becomes available. These channels differ greatly in the semantics of the
511 /// sender from asynchronous channels, however.
512 ///
513 /// This channel has an internal buffer on which messages will be queued. When
514 /// the internal buffer becomes full, future sends will *block* waiting for the
515 /// buffer to open up. Note that a buffer size of 0 is valid, in which case this
516 /// becomes  "rendezvous channel" where each send will not return until a recv
517 /// is paired with it.
518 ///
519 /// As with asynchronous channels, all senders will fail in `send` if the
520 /// `Receiver` has been destroyed.
521 ///
522 /// # Example
523 ///
524 /// ```
525 /// let (tx, rx) = sync_channel(1);
526 ///
527 /// // this returns immediately
528 /// tx.send(1i);
529 ///
530 /// spawn(proc() {
531 ///     // this will block until the previous message has been received
532 ///     tx.send(2i);
533 /// });
534 ///
535 /// assert_eq!(rx.recv(), 1i);
536 /// assert_eq!(rx.recv(), 2i);
537 /// ```
538 #[unstable = "this function may be renamed to more accurately reflect the type \
539               of channel that is is creating"]
540 pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) {
541     let a = Arc::new(UnsafeCell::new(sync::Packet::new(bound)));
542     (SyncSender::new(a.clone()), Receiver::new(Sync(a)))
543 }
544
545 ////////////////////////////////////////////////////////////////////////////////
546 // Sender
547 ////////////////////////////////////////////////////////////////////////////////
548
549 impl<T: Send> Sender<T> {
550     fn new(inner: Flavor<T>) -> Sender<T> {
551         Sender {
552             inner: UnsafeCell::new(inner),
553             sends: Cell::new(0),
554             marker: marker::NoSync,
555         }
556     }
557
558     /// Sends a value along this channel to be received by the corresponding
559     /// receiver.
560     ///
561     /// Rust channels are infinitely buffered so this method will never block.
562     ///
563     /// # Failure
564     ///
565     /// This function will fail if the other end of the channel has hung up.
566     /// This means that if the corresponding receiver has fallen out of scope,
567     /// this function will trigger a fail message saying that a message is
568     /// being sent on a closed channel.
569     ///
570     /// Note that if this function does *not* fail, it does not mean that the
571     /// data will be successfully received. All sends are placed into a queue,
572     /// so it is possible for a send to succeed (the other end is alive), but
573     /// then the other end could immediately disconnect.
574     ///
575     /// The purpose of this functionality is to propagate failure among tasks.
576     /// If failure is not desired, then consider using the `send_opt` method
577     #[experimental = "this function is being considered candidate for removal \
578                       to adhere to the general guidelines of rust"]
579     pub fn send(&self, t: T) {
580         if self.send_opt(t).is_err() {
581             fail!("sending on a closed channel");
582         }
583     }
584
585     /// Attempts to send a value on this channel, returning it back if it could
586     /// not be sent.
587     ///
588     /// A successful send occurs when it is determined that the other end of
589     /// the channel has not hung up already. An unsuccessful send would be one
590     /// where the corresponding receiver has already been deallocated. Note
591     /// that a return value of `Err` means that the data will never be
592     /// received, but a return value of `Ok` does *not* mean that the data
593     /// will be received.  It is possible for the corresponding receiver to
594     /// hang up immediately after this function returns `Ok`.
595     ///
596     /// Like `send`, this method will never block.
597     ///
598     /// # Failure
599     ///
600     /// This method will never fail, it will return the message back to the
601     /// caller if the other end is disconnected
602     ///
603     /// # Example
604     ///
605     /// ```
606     /// let (tx, rx) = channel();
607     ///
608     /// // This send is always successful
609     /// assert_eq!(tx.send_opt(1i), Ok(()));
610     ///
611     /// // This send will fail because the receiver is gone
612     /// drop(rx);
613     /// assert_eq!(tx.send_opt(1i), Err(1));
614     /// ```
615     #[unstable = "this function may be renamed to send() in the future"]
616     pub fn send_opt(&self, t: T) -> Result<(), T> {
617         // In order to prevent starvation of other tasks in situations where
618         // a task sends repeatedly without ever receiving, we occasionally
619         // yield instead of doing a send immediately.
620         //
621         // Don't unconditionally attempt to yield because the TLS overhead can
622         // be a bit much, and also use `try_take` instead of `take` because
623         // there's no reason that this send shouldn't be usable off the
624         // runtime.
625         let cnt = self.sends.get() + 1;
626         self.sends.set(cnt);
627         if cnt % (RESCHED_FREQ as uint) == 0 {
628             let task: Option<Box<Task>> = Local::try_take();
629             task.map(|t| t.maybe_yield());
630         }
631
632         let (new_inner, ret) = match *unsafe { self.inner() } {
633             Oneshot(ref p) => {
634                 unsafe {
635                     let p = p.get();
636                     if !(*p).sent() {
637                         return (*p).send(t);
638                     } else {
639                         let a = Arc::new(UnsafeCell::new(stream::Packet::new()));
640                         match (*p).upgrade(Receiver::new(Stream(a.clone()))) {
641                             oneshot::UpSuccess => {
642                                 let ret = (*a.get()).send(t);
643                                 (a, ret)
644                             }
645                             oneshot::UpDisconnected => (a, Err(t)),
646                             oneshot::UpWoke(task) => {
647                                 // This send cannot fail because the task is
648                                 // asleep (we're looking at it), so the receiver
649                                 // can't go away.
650                                 (*a.get()).send(t).ok().unwrap();
651                                 task.wake().map(|t| t.reawaken());
652                                 (a, Ok(()))
653                             }
654                         }
655                     }
656                 }
657             }
658             Stream(ref p) => return unsafe { (*p.get()).send(t) },
659             Shared(ref p) => return unsafe { (*p.get()).send(t) },
660             Sync(..) => unreachable!(),
661         };
662
663         unsafe {
664             let tmp = Sender::new(Stream(new_inner));
665             mem::swap(self.mut_inner(), tmp.mut_inner());
666         }
667         return ret;
668     }
669 }
670
671 #[unstable]
672 impl<T: Send> Clone for Sender<T> {
673     fn clone(&self) -> Sender<T> {
674         let (packet, sleeper) = match *unsafe { self.inner() } {
675             Oneshot(ref p) => {
676                 let a = Arc::new(UnsafeCell::new(shared::Packet::new()));
677                 unsafe {
678                     (*a.get()).postinit_lock();
679                     match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
680                         oneshot::UpSuccess | oneshot::UpDisconnected => (a, None),
681                         oneshot::UpWoke(task) => (a, Some(task))
682                     }
683                 }
684             }
685             Stream(ref p) => {
686                 let a = Arc::new(UnsafeCell::new(shared::Packet::new()));
687                 unsafe {
688                     (*a.get()).postinit_lock();
689                     match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
690                         stream::UpSuccess | stream::UpDisconnected => (a, None),
691                         stream::UpWoke(task) => (a, Some(task)),
692                     }
693                 }
694             }
695             Shared(ref p) => {
696                 unsafe { (*p.get()).clone_chan(); }
697                 return Sender::new(Shared(p.clone()));
698             }
699             Sync(..) => unreachable!(),
700         };
701
702         unsafe {
703             (*packet.get()).inherit_blocker(sleeper);
704
705             let tmp = Sender::new(Shared(packet.clone()));
706             mem::swap(self.mut_inner(), tmp.mut_inner());
707         }
708         Sender::new(Shared(packet))
709     }
710 }
711
712 #[unsafe_destructor]
713 impl<T: Send> Drop for Sender<T> {
714     fn drop(&mut self) {
715         match *unsafe { self.mut_inner() } {
716             Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); },
717             Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); },
718             Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); },
719             Sync(..) => unreachable!(),
720         }
721     }
722 }
723
724 ////////////////////////////////////////////////////////////////////////////////
725 // SyncSender
726 ////////////////////////////////////////////////////////////////////////////////
727
728 impl<T: Send> SyncSender<T> {
729     fn new(inner: Arc<UnsafeCell<sync::Packet<T>>>) -> SyncSender<T> {
730         SyncSender { inner: inner, marker: marker::NoSync }
731     }
732
733     /// Sends a value on this synchronous channel.
734     ///
735     /// This function will *block* until space in the internal buffer becomes
736     /// available or a receiver is available to hand off the message to.
737     ///
738     /// Note that a successful send does *not* guarantee that the receiver will
739     /// ever see the data if there is a buffer on this channel. Messages may be
740     /// enqueued in the internal buffer for the receiver to receive at a later
741     /// time. If the buffer size is 0, however, it can be guaranteed that the
742     /// receiver has indeed received the data if this function returns success.
743     ///
744     /// # Failure
745     ///
746     /// Similarly to `Sender::send`, this function will fail if the
747     /// corresponding `Receiver` for this channel has disconnected. This
748     /// behavior is used to propagate failure among tasks.
749     ///
750     /// If failure is not desired, you can achieve the same semantics with the
751     /// `SyncSender::send_opt` method which will not fail if the receiver
752     /// disconnects.
753     #[experimental = "this function is being considered candidate for removal \
754                       to adhere to the general guidelines of rust"]
755     pub fn send(&self, t: T) {
756         if self.send_opt(t).is_err() {
757             fail!("sending on a closed channel");
758         }
759     }
760
761     /// Send a value on a channel, returning it back if the receiver
762     /// disconnected
763     ///
764     /// This method will *block* to send the value `t` on the channel, but if
765     /// the value could not be sent due to the receiver disconnecting, the value
766     /// is returned back to the callee. This function is similar to `try_send`,
767     /// except that it will block if the channel is currently full.
768     ///
769     /// # Failure
770     ///
771     /// This function cannot fail.
772     #[unstable = "this function may be renamed to send() in the future"]
773     pub fn send_opt(&self, t: T) -> Result<(), T> {
774         unsafe { (*self.inner.get()).send(t) }
775     }
776
777     /// Attempts to send a value on this channel without blocking.
778     ///
779     /// This method differs from `send_opt` by returning immediately if the
780     /// channel's buffer is full or no receiver is waiting to acquire some
781     /// data. Compared with `send_opt`, this function has two failure cases
782     /// instead of one (one for disconnection, one for a full buffer).
783     ///
784     /// See `SyncSender::send` for notes about guarantees of whether the
785     /// receiver has received the data or not if this function is successful.
786     ///
787     /// # Failure
788     ///
789     /// This function cannot fail
790     #[unstable = "the return type of this function is candidate for \
791                   modification"]
792     pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
793         unsafe { (*self.inner.get()).try_send(t) }
794     }
795 }
796
797 #[unstable]
798 impl<T: Send> Clone for SyncSender<T> {
799     fn clone(&self) -> SyncSender<T> {
800         unsafe { (*self.inner.get()).clone_chan(); }
801         return SyncSender::new(self.inner.clone());
802     }
803 }
804
805 #[unsafe_destructor]
806 impl<T: Send> Drop for SyncSender<T> {
807     fn drop(&mut self) {
808         unsafe { (*self.inner.get()).drop_chan(); }
809     }
810 }
811
812 ////////////////////////////////////////////////////////////////////////////////
813 // Receiver
814 ////////////////////////////////////////////////////////////////////////////////
815
816 impl<T: Send> Receiver<T> {
817     fn new(inner: Flavor<T>) -> Receiver<T> {
818         Receiver { inner: UnsafeCell::new(inner), receives: Cell::new(0), marker: marker::NoSync }
819     }
820
821     /// Blocks waiting for a value on this receiver
822     ///
823     /// This function will block if necessary to wait for a corresponding send
824     /// on the channel from its paired `Sender` structure. This receiver will
825     /// be woken up when data is ready, and the data will be returned.
826     ///
827     /// # Failure
828     ///
829     /// Similar to channels, this method will trigger a task failure if the
830     /// other end of the channel has hung up (been deallocated). The purpose of
831     /// this is to propagate failure among tasks.
832     ///
833     /// If failure is not desired, then there are two options:
834     ///
835     /// * If blocking is still desired, the `recv_opt` method will return `None`
836     ///   when the other end hangs up
837     ///
838     /// * If blocking is not desired, then the `try_recv` method will attempt to
839     ///   peek at a value on this receiver.
840     #[experimental = "this function is being considered candidate for removal \
841                       to adhere to the general guidelines of rust"]
842     pub fn recv(&self) -> T {
843         match self.recv_opt() {
844             Ok(t) => t,
845             Err(()) => fail!("receiving on a closed channel"),
846         }
847     }
848
849     /// Attempts to return a pending value on this receiver without blocking
850     ///
851     /// This method will never block the caller in order to wait for data to
852     /// become available. Instead, this will always return immediately with a
853     /// possible option of pending data on the channel.
854     ///
855     /// This is useful for a flavor of "optimistic check" before deciding to
856     /// block on a receiver.
857     ///
858     /// This function cannot fail.
859     #[unstable = "the return type of this function may be altered"]
860     pub fn try_recv(&self) -> Result<T, TryRecvError> {
861         // If a thread is spinning in try_recv, we should take the opportunity
862         // to reschedule things occasionally. See notes above in scheduling on
863         // sends for why this doesn't always hit TLS, and also for why this uses
864         // `try_take` instead of `take`.
865         let cnt = self.receives.get() + 1;
866         self.receives.set(cnt);
867         if cnt % (RESCHED_FREQ as uint) == 0 {
868             let task: Option<Box<Task>> = Local::try_take();
869             task.map(|t| t.maybe_yield());
870         }
871
872         loop {
873             let new_port = match *unsafe { self.inner() } {
874                 Oneshot(ref p) => {
875                     match unsafe { (*p.get()).try_recv() } {
876                         Ok(t) => return Ok(t),
877                         Err(oneshot::Empty) => return Err(Empty),
878                         Err(oneshot::Disconnected) => return Err(Disconnected),
879                         Err(oneshot::Upgraded(rx)) => rx,
880                     }
881                 }
882                 Stream(ref p) => {
883                     match unsafe { (*p.get()).try_recv() } {
884                         Ok(t) => return Ok(t),
885                         Err(stream::Empty) => return Err(Empty),
886                         Err(stream::Disconnected) => return Err(Disconnected),
887                         Err(stream::Upgraded(rx)) => rx,
888                     }
889                 }
890                 Shared(ref p) => {
891                     match unsafe { (*p.get()).try_recv() } {
892                         Ok(t) => return Ok(t),
893                         Err(shared::Empty) => return Err(Empty),
894                         Err(shared::Disconnected) => return Err(Disconnected),
895                     }
896                 }
897                 Sync(ref p) => {
898                     match unsafe { (*p.get()).try_recv() } {
899                         Ok(t) => return Ok(t),
900                         Err(sync::Empty) => return Err(Empty),
901                         Err(sync::Disconnected) => return Err(Disconnected),
902                     }
903                 }
904             };
905             unsafe {
906                 mem::swap(self.mut_inner(),
907                           new_port.mut_inner());
908             }
909         }
910     }
911
912     /// Attempt to wait for a value on this receiver, but does not fail if the
913     /// corresponding channel has hung up.
914     ///
915     /// This implementation of iterators for ports will always block if there is
916     /// not data available on the receiver, but it will not fail in the case
917     /// that the channel has been deallocated.
918     ///
919     /// In other words, this function has the same semantics as the `recv`
920     /// method except for the failure aspect.
921     ///
922     /// If the channel has hung up, then `Err` is returned. Otherwise `Ok` of
923     /// the value found on the receiver is returned.
924     #[unstable = "this function may be renamed to recv()"]
925     pub fn recv_opt(&self) -> Result<T, ()> {
926         loop {
927             let new_port = match *unsafe { self.inner() } {
928                 Oneshot(ref p) => {
929                     match unsafe { (*p.get()).recv() } {
930                         Ok(t) => return Ok(t),
931                         Err(oneshot::Empty) => return unreachable!(),
932                         Err(oneshot::Disconnected) => return Err(()),
933                         Err(oneshot::Upgraded(rx)) => rx,
934                     }
935                 }
936                 Stream(ref p) => {
937                     match unsafe { (*p.get()).recv() } {
938                         Ok(t) => return Ok(t),
939                         Err(stream::Empty) => return unreachable!(),
940                         Err(stream::Disconnected) => return Err(()),
941                         Err(stream::Upgraded(rx)) => rx,
942                     }
943                 }
944                 Shared(ref p) => {
945                     match unsafe { (*p.get()).recv() } {
946                         Ok(t) => return Ok(t),
947                         Err(shared::Empty) => return unreachable!(),
948                         Err(shared::Disconnected) => return Err(()),
949                     }
950                 }
951                 Sync(ref p) => return unsafe { (*p.get()).recv() }
952             };
953             unsafe {
954                 mem::swap(self.mut_inner(), new_port.mut_inner());
955             }
956         }
957     }
958
959     /// Returns an iterator which will block waiting for messages, but never
960     /// `fail!`. It will return `None` when the channel has hung up.
961     #[unstable]
962     pub fn iter<'a>(&'a self) -> Messages<'a, T> {
963         Messages { rx: self }
964     }
965 }
966
967 impl<T: Send> select::Packet for Receiver<T> {
968     fn can_recv(&self) -> bool {
969         loop {
970             let new_port = match *unsafe { self.inner() } {
971                 Oneshot(ref p) => {
972                     match unsafe { (*p.get()).can_recv() } {
973                         Ok(ret) => return ret,
974                         Err(upgrade) => upgrade,
975                     }
976                 }
977                 Stream(ref p) => {
978                     match unsafe { (*p.get()).can_recv() } {
979                         Ok(ret) => return ret,
980                         Err(upgrade) => upgrade,
981                     }
982                 }
983                 Shared(ref p) => {
984                     return unsafe { (*p.get()).can_recv() };
985                 }
986                 Sync(ref p) => {
987                     return unsafe { (*p.get()).can_recv() };
988                 }
989             };
990             unsafe {
991                 mem::swap(self.mut_inner(),
992                           new_port.mut_inner());
993             }
994         }
995     }
996
997     fn start_selection(&self, mut task: BlockedTask) -> Result<(), BlockedTask>{
998         loop {
999             let (t, new_port) = match *unsafe { self.inner() } {
1000                 Oneshot(ref p) => {
1001                     match unsafe { (*p.get()).start_selection(task) } {
1002                         oneshot::SelSuccess => return Ok(()),
1003                         oneshot::SelCanceled(task) => return Err(task),
1004                         oneshot::SelUpgraded(t, rx) => (t, rx),
1005                     }
1006                 }
1007                 Stream(ref p) => {
1008                     match unsafe { (*p.get()).start_selection(task) } {
1009                         stream::SelSuccess => return Ok(()),
1010                         stream::SelCanceled(task) => return Err(task),
1011                         stream::SelUpgraded(t, rx) => (t, rx),
1012                     }
1013                 }
1014                 Shared(ref p) => {
1015                     return unsafe { (*p.get()).start_selection(task) };
1016                 }
1017                 Sync(ref p) => {
1018                     return unsafe { (*p.get()).start_selection(task) };
1019                 }
1020             };
1021             task = t;
1022             unsafe {
1023                 mem::swap(self.mut_inner(),
1024                           new_port.mut_inner());
1025             }
1026         }
1027     }
1028
1029     fn abort_selection(&self) -> bool {
1030         let mut was_upgrade = false;
1031         loop {
1032             let result = match *unsafe { self.inner() } {
1033                 Oneshot(ref p) => unsafe { (*p.get()).abort_selection() },
1034                 Stream(ref p) => unsafe {
1035                     (*p.get()).abort_selection(was_upgrade)
1036                 },
1037                 Shared(ref p) => return unsafe {
1038                     (*p.get()).abort_selection(was_upgrade)
1039                 },
1040                 Sync(ref p) => return unsafe {
1041                     (*p.get()).abort_selection()
1042                 },
1043             };
1044             let new_port = match result { Ok(b) => return b, Err(p) => p };
1045             was_upgrade = true;
1046             unsafe {
1047                 mem::swap(self.mut_inner(),
1048                           new_port.mut_inner());
1049             }
1050         }
1051     }
1052 }
1053
1054 #[unstable]
1055 impl<'a, T: Send> Iterator<T> for Messages<'a, T> {
1056     fn next(&mut self) -> Option<T> { self.rx.recv_opt().ok() }
1057 }
1058
1059 #[unsafe_destructor]
1060 impl<T: Send> Drop for Receiver<T> {
1061     fn drop(&mut self) {
1062         match *unsafe { self.mut_inner() } {
1063             Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); },
1064             Stream(ref mut p) => unsafe { (*p.get()).drop_port(); },
1065             Shared(ref mut p) => unsafe { (*p.get()).drop_port(); },
1066             Sync(ref mut p) => unsafe { (*p.get()).drop_port(); },
1067         }
1068     }
1069 }
1070
1071 #[cfg(test)]
1072 mod test {
1073     use std::prelude::*;
1074
1075     use native;
1076     use std::os;
1077     use super::*;
1078
1079     pub fn stress_factor() -> uint {
1080         match os::getenv("RUST_TEST_STRESS") {
1081             Some(val) => from_str::<uint>(val.as_slice()).unwrap(),
1082             None => 1,
1083         }
1084     }
1085
1086     test!(fn smoke() {
1087         let (tx, rx) = channel::<int>();
1088         tx.send(1);
1089         assert_eq!(rx.recv(), 1);
1090     })
1091
1092     test!(fn drop_full() {
1093         let (tx, _rx) = channel();
1094         tx.send(box 1i);
1095     })
1096
1097     test!(fn drop_full_shared() {
1098         let (tx, _rx) = channel();
1099         drop(tx.clone());
1100         drop(tx.clone());
1101         tx.send(box 1i);
1102     })
1103
1104     test!(fn smoke_shared() {
1105         let (tx, rx) = channel::<int>();
1106         tx.send(1);
1107         assert_eq!(rx.recv(), 1);
1108         let tx = tx.clone();
1109         tx.send(1);
1110         assert_eq!(rx.recv(), 1);
1111     })
1112
1113     test!(fn smoke_threads() {
1114         let (tx, rx) = channel::<int>();
1115         spawn(proc() {
1116             tx.send(1);
1117         });
1118         assert_eq!(rx.recv(), 1);
1119     })
1120
1121     test!(fn smoke_port_gone() {
1122         let (tx, rx) = channel::<int>();
1123         drop(rx);
1124         tx.send(1);
1125     } #[should_fail])
1126
1127     test!(fn smoke_shared_port_gone() {
1128         let (tx, rx) = channel::<int>();
1129         drop(rx);
1130         tx.send(1);
1131     } #[should_fail])
1132
1133     test!(fn smoke_shared_port_gone2() {
1134         let (tx, rx) = channel::<int>();
1135         drop(rx);
1136         let tx2 = tx.clone();
1137         drop(tx);
1138         tx2.send(1);
1139     } #[should_fail])
1140
1141     test!(fn port_gone_concurrent() {
1142         let (tx, rx) = channel::<int>();
1143         spawn(proc() {
1144             rx.recv();
1145         });
1146         loop { tx.send(1) }
1147     } #[should_fail])
1148
1149     test!(fn port_gone_concurrent_shared() {
1150         let (tx, rx) = channel::<int>();
1151         let tx2 = tx.clone();
1152         spawn(proc() {
1153             rx.recv();
1154         });
1155         loop {
1156             tx.send(1);
1157             tx2.send(1);
1158         }
1159     } #[should_fail])
1160
1161     test!(fn smoke_chan_gone() {
1162         let (tx, rx) = channel::<int>();
1163         drop(tx);
1164         rx.recv();
1165     } #[should_fail])
1166
1167     test!(fn smoke_chan_gone_shared() {
1168         let (tx, rx) = channel::<()>();
1169         let tx2 = tx.clone();
1170         drop(tx);
1171         drop(tx2);
1172         rx.recv();
1173     } #[should_fail])
1174
1175     test!(fn chan_gone_concurrent() {
1176         let (tx, rx) = channel::<int>();
1177         spawn(proc() {
1178             tx.send(1);
1179             tx.send(1);
1180         });
1181         loop { rx.recv(); }
1182     } #[should_fail])
1183
1184     test!(fn stress() {
1185         let (tx, rx) = channel::<int>();
1186         spawn(proc() {
1187             for _ in range(0u, 10000) { tx.send(1i); }
1188         });
1189         for _ in range(0u, 10000) {
1190             assert_eq!(rx.recv(), 1);
1191         }
1192     })
1193
1194     test!(fn stress_shared() {
1195         static AMT: uint = 10000;
1196         static NTHREADS: uint = 8;
1197         let (tx, rx) = channel::<int>();
1198         let (dtx, drx) = channel::<()>();
1199
1200         spawn(proc() {
1201             for _ in range(0, AMT * NTHREADS) {
1202                 assert_eq!(rx.recv(), 1);
1203             }
1204             match rx.try_recv() {
1205                 Ok(..) => fail!(),
1206                 _ => {}
1207             }
1208             dtx.send(());
1209         });
1210
1211         for _ in range(0, NTHREADS) {
1212             let tx = tx.clone();
1213             spawn(proc() {
1214                 for _ in range(0, AMT) { tx.send(1); }
1215             });
1216         }
1217         drop(tx);
1218         drx.recv();
1219     })
1220
1221     #[test]
1222     fn send_from_outside_runtime() {
1223         let (tx1, rx1) = channel::<()>();
1224         let (tx2, rx2) = channel::<int>();
1225         let (tx3, rx3) = channel::<()>();
1226         let tx4 = tx3.clone();
1227         spawn(proc() {
1228             tx1.send(());
1229             for _ in range(0i, 40) {
1230                 assert_eq!(rx2.recv(), 1);
1231             }
1232             tx3.send(());
1233         });
1234         rx1.recv();
1235         native::task::spawn(proc() {
1236             for _ in range(0i, 40) {
1237                 tx2.send(1);
1238             }
1239             tx4.send(());
1240         });
1241         rx3.recv();
1242         rx3.recv();
1243     }
1244
1245     #[test]
1246     fn recv_from_outside_runtime() {
1247         let (tx, rx) = channel::<int>();
1248         let (dtx, drx) = channel();
1249         native::task::spawn(proc() {
1250             for _ in range(0i, 40) {
1251                 assert_eq!(rx.recv(), 1);
1252             }
1253             dtx.send(());
1254         });
1255         for _ in range(0u, 40) {
1256             tx.send(1);
1257         }
1258         drx.recv();
1259     }
1260
1261     #[test]
1262     fn no_runtime() {
1263         let (tx1, rx1) = channel::<int>();
1264         let (tx2, rx2) = channel::<int>();
1265         let (tx3, rx3) = channel::<()>();
1266         let tx4 = tx3.clone();
1267         native::task::spawn(proc() {
1268             assert_eq!(rx1.recv(), 1);
1269             tx2.send(2);
1270             tx4.send(());
1271         });
1272         native::task::spawn(proc() {
1273             tx1.send(1);
1274             assert_eq!(rx2.recv(), 2);
1275             tx3.send(());
1276         });
1277         rx3.recv();
1278         rx3.recv();
1279     }
1280
1281     test!(fn oneshot_single_thread_close_port_first() {
1282         // Simple test of closing without sending
1283         let (_tx, rx) = channel::<int>();
1284         drop(rx);
1285     })
1286
1287     test!(fn oneshot_single_thread_close_chan_first() {
1288         // Simple test of closing without sending
1289         let (tx, _rx) = channel::<int>();
1290         drop(tx);
1291     })
1292
1293     test!(fn oneshot_single_thread_send_port_close() {
1294         // Testing that the sender cleans up the payload if receiver is closed
1295         let (tx, rx) = channel::<Box<int>>();
1296         drop(rx);
1297         tx.send(box 0);
1298     } #[should_fail])
1299
1300     test!(fn oneshot_single_thread_recv_chan_close() {
1301         // Receiving on a closed chan will fail
1302         let res = task::try(proc() {
1303             let (tx, rx) = channel::<int>();
1304             drop(tx);
1305             rx.recv();
1306         });
1307         // What is our res?
1308         assert!(res.is_err());
1309     })
1310
1311     test!(fn oneshot_single_thread_send_then_recv() {
1312         let (tx, rx) = channel::<Box<int>>();
1313         tx.send(box 10);
1314         assert!(rx.recv() == box 10);
1315     })
1316
1317     test!(fn oneshot_single_thread_try_send_open() {
1318         let (tx, rx) = channel::<int>();
1319         assert!(tx.send_opt(10).is_ok());
1320         assert!(rx.recv() == 10);
1321     })
1322
1323     test!(fn oneshot_single_thread_try_send_closed() {
1324         let (tx, rx) = channel::<int>();
1325         drop(rx);
1326         assert!(tx.send_opt(10).is_err());
1327     })
1328
1329     test!(fn oneshot_single_thread_try_recv_open() {
1330         let (tx, rx) = channel::<int>();
1331         tx.send(10);
1332         assert!(rx.recv_opt() == Ok(10));
1333     })
1334
1335     test!(fn oneshot_single_thread_try_recv_closed() {
1336         let (tx, rx) = channel::<int>();
1337         drop(tx);
1338         assert!(rx.recv_opt() == Err(()));
1339     })
1340
1341     test!(fn oneshot_single_thread_peek_data() {
1342         let (tx, rx) = channel::<int>();
1343         assert_eq!(rx.try_recv(), Err(Empty))
1344         tx.send(10);
1345         assert_eq!(rx.try_recv(), Ok(10));
1346     })
1347
1348     test!(fn oneshot_single_thread_peek_close() {
1349         let (tx, rx) = channel::<int>();
1350         drop(tx);
1351         assert_eq!(rx.try_recv(), Err(Disconnected));
1352         assert_eq!(rx.try_recv(), Err(Disconnected));
1353     })
1354
1355     test!(fn oneshot_single_thread_peek_open() {
1356         let (_tx, rx) = channel::<int>();
1357         assert_eq!(rx.try_recv(), Err(Empty));
1358     })
1359
1360     test!(fn oneshot_multi_task_recv_then_send() {
1361         let (tx, rx) = channel::<Box<int>>();
1362         spawn(proc() {
1363             assert!(rx.recv() == box 10);
1364         });
1365
1366         tx.send(box 10);
1367     })
1368
1369     test!(fn oneshot_multi_task_recv_then_close() {
1370         let (tx, rx) = channel::<Box<int>>();
1371         spawn(proc() {
1372             drop(tx);
1373         });
1374         let res = task::try(proc() {
1375             assert!(rx.recv() == box 10);
1376         });
1377         assert!(res.is_err());
1378     })
1379
1380     test!(fn oneshot_multi_thread_close_stress() {
1381         for _ in range(0, stress_factor()) {
1382             let (tx, rx) = channel::<int>();
1383             spawn(proc() {
1384                 drop(rx);
1385             });
1386             drop(tx);
1387         }
1388     })
1389
1390     test!(fn oneshot_multi_thread_send_close_stress() {
1391         for _ in range(0, stress_factor()) {
1392             let (tx, rx) = channel::<int>();
1393             spawn(proc() {
1394                 drop(rx);
1395             });
1396             let _ = task::try(proc() {
1397                 tx.send(1);
1398             });
1399         }
1400     })
1401
1402     test!(fn oneshot_multi_thread_recv_close_stress() {
1403         for _ in range(0, stress_factor()) {
1404             let (tx, rx) = channel::<int>();
1405             spawn(proc() {
1406                 let res = task::try(proc() {
1407                     rx.recv();
1408                 });
1409                 assert!(res.is_err());
1410             });
1411             spawn(proc() {
1412                 spawn(proc() {
1413                     drop(tx);
1414                 });
1415             });
1416         }
1417     })
1418
1419     test!(fn oneshot_multi_thread_send_recv_stress() {
1420         for _ in range(0, stress_factor()) {
1421             let (tx, rx) = channel();
1422             spawn(proc() {
1423                 tx.send(box 10i);
1424             });
1425             spawn(proc() {
1426                 assert!(rx.recv() == box 10i);
1427             });
1428         }
1429     })
1430
1431     test!(fn stream_send_recv_stress() {
1432         for _ in range(0, stress_factor()) {
1433             let (tx, rx) = channel();
1434
1435             send(tx, 0);
1436             recv(rx, 0);
1437
1438             fn send(tx: Sender<Box<int>>, i: int) {
1439                 if i == 10 { return }
1440
1441                 spawn(proc() {
1442                     tx.send(box i);
1443                     send(tx, i + 1);
1444                 });
1445             }
1446
1447             fn recv(rx: Receiver<Box<int>>, i: int) {
1448                 if i == 10 { return }
1449
1450                 spawn(proc() {
1451                     assert!(rx.recv() == box i);
1452                     recv(rx, i + 1);
1453                 });
1454             }
1455         }
1456     })
1457
1458     test!(fn recv_a_lot() {
1459         // Regression test that we don't run out of stack in scheduler context
1460         let (tx, rx) = channel();
1461         for _ in range(0i, 10000) { tx.send(()); }
1462         for _ in range(0i, 10000) { rx.recv(); }
1463     })
1464
1465     test!(fn shared_chan_stress() {
1466         let (tx, rx) = channel();
1467         let total = stress_factor() + 100;
1468         for _ in range(0, total) {
1469             let tx = tx.clone();
1470             spawn(proc() {
1471                 tx.send(());
1472             });
1473         }
1474
1475         for _ in range(0, total) {
1476             rx.recv();
1477         }
1478     })
1479
1480     test!(fn test_nested_recv_iter() {
1481         let (tx, rx) = channel::<int>();
1482         let (total_tx, total_rx) = channel::<int>();
1483
1484         spawn(proc() {
1485             let mut acc = 0;
1486             for x in rx.iter() {
1487                 acc += x;
1488             }
1489             total_tx.send(acc);
1490         });
1491
1492         tx.send(3);
1493         tx.send(1);
1494         tx.send(2);
1495         drop(tx);
1496         assert_eq!(total_rx.recv(), 6);
1497     })
1498
1499     test!(fn test_recv_iter_break() {
1500         let (tx, rx) = channel::<int>();
1501         let (count_tx, count_rx) = channel();
1502
1503         spawn(proc() {
1504             let mut count = 0;
1505             for x in rx.iter() {
1506                 if count >= 3 {
1507                     break;
1508                 } else {
1509                     count += x;
1510                 }
1511             }
1512             count_tx.send(count);
1513         });
1514
1515         tx.send(2);
1516         tx.send(2);
1517         tx.send(2);
1518         let _ = tx.send_opt(2);
1519         drop(tx);
1520         assert_eq!(count_rx.recv(), 4);
1521     })
1522
1523     test!(fn try_recv_states() {
1524         let (tx1, rx1) = channel::<int>();
1525         let (tx2, rx2) = channel::<()>();
1526         let (tx3, rx3) = channel::<()>();
1527         spawn(proc() {
1528             rx2.recv();
1529             tx1.send(1);
1530             tx3.send(());
1531             rx2.recv();
1532             drop(tx1);
1533             tx3.send(());
1534         });
1535
1536         assert_eq!(rx1.try_recv(), Err(Empty));
1537         tx2.send(());
1538         rx3.recv();
1539         assert_eq!(rx1.try_recv(), Ok(1));
1540         assert_eq!(rx1.try_recv(), Err(Empty));
1541         tx2.send(());
1542         rx3.recv();
1543         assert_eq!(rx1.try_recv(), Err(Disconnected));
1544     })
1545
1546     // This bug used to end up in a livelock inside of the Receiver destructor
1547     // because the internal state of the Shared packet was corrupted
1548     test!(fn destroy_upgraded_shared_port_when_sender_still_active() {
1549         let (tx, rx) = channel();
1550         let (tx2, rx2) = channel();
1551         spawn(proc() {
1552             rx.recv(); // wait on a oneshot
1553             drop(rx);  // destroy a shared
1554             tx2.send(());
1555         });
1556         // make sure the other task has gone to sleep
1557         for _ in range(0u, 5000) { task::deschedule(); }
1558
1559         // upgrade to a shared chan and send a message
1560         let t = tx.clone();
1561         drop(tx);
1562         t.send(());
1563
1564         // wait for the child task to exit before we exit
1565         rx2.recv();
1566     })
1567
1568     test!(fn sends_off_the_runtime() {
1569         use std::rt::thread::Thread;
1570
1571         let (tx, rx) = channel();
1572         let t = Thread::start(proc() {
1573             for _ in range(0u, 1000) {
1574                 tx.send(());
1575             }
1576         });
1577         for _ in range(0u, 1000) {
1578             rx.recv();
1579         }
1580         t.join();
1581     })
1582
1583     test!(fn try_recvs_off_the_runtime() {
1584         use std::rt::thread::Thread;
1585
1586         let (tx, rx) = channel();
1587         let (cdone, pdone) = channel();
1588         let t = Thread::start(proc() {
1589             let mut hits = 0u;
1590             while hits < 10 {
1591                 match rx.try_recv() {
1592                     Ok(()) => { hits += 1; }
1593                     Err(Empty) => { Thread::yield_now(); }
1594                     Err(Disconnected) => return,
1595                 }
1596             }
1597             cdone.send(());
1598         });
1599         for _ in range(0u, 10) {
1600             tx.send(());
1601         }
1602         t.join();
1603         pdone.recv();
1604     })
1605 }
1606
1607 #[cfg(test)]
1608 mod sync_tests {
1609     use std::prelude::*;
1610     use std::os;
1611
1612     pub fn stress_factor() -> uint {
1613         match os::getenv("RUST_TEST_STRESS") {
1614             Some(val) => from_str::<uint>(val.as_slice()).unwrap(),
1615             None => 1,
1616         }
1617     }
1618
1619     test!(fn smoke() {
1620         let (tx, rx) = sync_channel::<int>(1);
1621         tx.send(1);
1622         assert_eq!(rx.recv(), 1);
1623     })
1624
1625     test!(fn drop_full() {
1626         let (tx, _rx) = sync_channel(1);
1627         tx.send(box 1i);
1628     })
1629
1630     test!(fn smoke_shared() {
1631         let (tx, rx) = sync_channel::<int>(1);
1632         tx.send(1);
1633         assert_eq!(rx.recv(), 1);
1634         let tx = tx.clone();
1635         tx.send(1);
1636         assert_eq!(rx.recv(), 1);
1637     })
1638
1639     test!(fn smoke_threads() {
1640         let (tx, rx) = sync_channel::<int>(0);
1641         spawn(proc() {
1642             tx.send(1);
1643         });
1644         assert_eq!(rx.recv(), 1);
1645     })
1646
1647     test!(fn smoke_port_gone() {
1648         let (tx, rx) = sync_channel::<int>(0);
1649         drop(rx);
1650         tx.send(1);
1651     } #[should_fail])
1652
1653     test!(fn smoke_shared_port_gone2() {
1654         let (tx, rx) = sync_channel::<int>(0);
1655         drop(rx);
1656         let tx2 = tx.clone();
1657         drop(tx);
1658         tx2.send(1);
1659     } #[should_fail])
1660
1661     test!(fn port_gone_concurrent() {
1662         let (tx, rx) = sync_channel::<int>(0);
1663         spawn(proc() {
1664             rx.recv();
1665         });
1666         loop { tx.send(1) }
1667     } #[should_fail])
1668
1669     test!(fn port_gone_concurrent_shared() {
1670         let (tx, rx) = sync_channel::<int>(0);
1671         let tx2 = tx.clone();
1672         spawn(proc() {
1673             rx.recv();
1674         });
1675         loop {
1676             tx.send(1);
1677             tx2.send(1);
1678         }
1679     } #[should_fail])
1680
1681     test!(fn smoke_chan_gone() {
1682         let (tx, rx) = sync_channel::<int>(0);
1683         drop(tx);
1684         rx.recv();
1685     } #[should_fail])
1686
1687     test!(fn smoke_chan_gone_shared() {
1688         let (tx, rx) = sync_channel::<()>(0);
1689         let tx2 = tx.clone();
1690         drop(tx);
1691         drop(tx2);
1692         rx.recv();
1693     } #[should_fail])
1694
1695     test!(fn chan_gone_concurrent() {
1696         let (tx, rx) = sync_channel::<int>(0);
1697         spawn(proc() {
1698             tx.send(1);
1699             tx.send(1);
1700         });
1701         loop { rx.recv(); }
1702     } #[should_fail])
1703
1704     test!(fn stress() {
1705         let (tx, rx) = sync_channel::<int>(0);
1706         spawn(proc() {
1707             for _ in range(0u, 10000) { tx.send(1); }
1708         });
1709         for _ in range(0u, 10000) {
1710             assert_eq!(rx.recv(), 1);
1711         }
1712     })
1713
1714     test!(fn stress_shared() {
1715         static AMT: uint = 1000;
1716         static NTHREADS: uint = 8;
1717         let (tx, rx) = sync_channel::<int>(0);
1718         let (dtx, drx) = sync_channel::<()>(0);
1719
1720         spawn(proc() {
1721             for _ in range(0, AMT * NTHREADS) {
1722                 assert_eq!(rx.recv(), 1);
1723             }
1724             match rx.try_recv() {
1725                 Ok(..) => fail!(),
1726                 _ => {}
1727             }
1728             dtx.send(());
1729         });
1730
1731         for _ in range(0, NTHREADS) {
1732             let tx = tx.clone();
1733             spawn(proc() {
1734                 for _ in range(0, AMT) { tx.send(1); }
1735             });
1736         }
1737         drop(tx);
1738         drx.recv();
1739     })
1740
1741     test!(fn oneshot_single_thread_close_port_first() {
1742         // Simple test of closing without sending
1743         let (_tx, rx) = sync_channel::<int>(0);
1744         drop(rx);
1745     })
1746
1747     test!(fn oneshot_single_thread_close_chan_first() {
1748         // Simple test of closing without sending
1749         let (tx, _rx) = sync_channel::<int>(0);
1750         drop(tx);
1751     })
1752
1753     test!(fn oneshot_single_thread_send_port_close() {
1754         // Testing that the sender cleans up the payload if receiver is closed
1755         let (tx, rx) = sync_channel::<Box<int>>(0);
1756         drop(rx);
1757         tx.send(box 0);
1758     } #[should_fail])
1759
1760     test!(fn oneshot_single_thread_recv_chan_close() {
1761         // Receiving on a closed chan will fail
1762         let res = task::try(proc() {
1763             let (tx, rx) = sync_channel::<int>(0);
1764             drop(tx);
1765             rx.recv();
1766         });
1767         // What is our res?
1768         assert!(res.is_err());
1769     })
1770
1771     test!(fn oneshot_single_thread_send_then_recv() {
1772         let (tx, rx) = sync_channel::<Box<int>>(1);
1773         tx.send(box 10);
1774         assert!(rx.recv() == box 10);
1775     })
1776
1777     test!(fn oneshot_single_thread_try_send_open() {
1778         let (tx, rx) = sync_channel::<int>(1);
1779         assert_eq!(tx.try_send(10), Ok(()));
1780         assert!(rx.recv() == 10);
1781     })
1782
1783     test!(fn oneshot_single_thread_try_send_closed() {
1784         let (tx, rx) = sync_channel::<int>(0);
1785         drop(rx);
1786         assert_eq!(tx.try_send(10), Err(RecvDisconnected(10)));
1787     })
1788
1789     test!(fn oneshot_single_thread_try_send_closed2() {
1790         let (tx, _rx) = sync_channel::<int>(0);
1791         assert_eq!(tx.try_send(10), Err(Full(10)));
1792     })
1793
1794     test!(fn oneshot_single_thread_try_recv_open() {
1795         let (tx, rx) = sync_channel::<int>(1);
1796         tx.send(10);
1797         assert!(rx.recv_opt() == Ok(10));
1798     })
1799
1800     test!(fn oneshot_single_thread_try_recv_closed() {
1801         let (tx, rx) = sync_channel::<int>(0);
1802         drop(tx);
1803         assert!(rx.recv_opt() == Err(()));
1804     })
1805
1806     test!(fn oneshot_single_thread_peek_data() {
1807         let (tx, rx) = sync_channel::<int>(1);
1808         assert_eq!(rx.try_recv(), Err(Empty))
1809         tx.send(10);
1810         assert_eq!(rx.try_recv(), Ok(10));
1811     })
1812
1813     test!(fn oneshot_single_thread_peek_close() {
1814         let (tx, rx) = sync_channel::<int>(0);
1815         drop(tx);
1816         assert_eq!(rx.try_recv(), Err(Disconnected));
1817         assert_eq!(rx.try_recv(), Err(Disconnected));
1818     })
1819
1820     test!(fn oneshot_single_thread_peek_open() {
1821         let (_tx, rx) = sync_channel::<int>(0);
1822         assert_eq!(rx.try_recv(), Err(Empty));
1823     })
1824
1825     test!(fn oneshot_multi_task_recv_then_send() {
1826         let (tx, rx) = sync_channel::<Box<int>>(0);
1827         spawn(proc() {
1828             assert!(rx.recv() == box 10);
1829         });
1830
1831         tx.send(box 10);
1832     })
1833
1834     test!(fn oneshot_multi_task_recv_then_close() {
1835         let (tx, rx) = sync_channel::<Box<int>>(0);
1836         spawn(proc() {
1837             drop(tx);
1838         });
1839         let res = task::try(proc() {
1840             assert!(rx.recv() == box 10);
1841         });
1842         assert!(res.is_err());
1843     })
1844
1845     test!(fn oneshot_multi_thread_close_stress() {
1846         for _ in range(0, stress_factor()) {
1847             let (tx, rx) = sync_channel::<int>(0);
1848             spawn(proc() {
1849                 drop(rx);
1850             });
1851             drop(tx);
1852         }
1853     })
1854
1855     test!(fn oneshot_multi_thread_send_close_stress() {
1856         for _ in range(0, stress_factor()) {
1857             let (tx, rx) = sync_channel::<int>(0);
1858             spawn(proc() {
1859                 drop(rx);
1860             });
1861             let _ = task::try(proc() {
1862                 tx.send(1);
1863             });
1864         }
1865     })
1866
1867     test!(fn oneshot_multi_thread_recv_close_stress() {
1868         for _ in range(0, stress_factor()) {
1869             let (tx, rx) = sync_channel::<int>(0);
1870             spawn(proc() {
1871                 let res = task::try(proc() {
1872                     rx.recv();
1873                 });
1874                 assert!(res.is_err());
1875             });
1876             spawn(proc() {
1877                 spawn(proc() {
1878                     drop(tx);
1879                 });
1880             });
1881         }
1882     })
1883
1884     test!(fn oneshot_multi_thread_send_recv_stress() {
1885         for _ in range(0, stress_factor()) {
1886             let (tx, rx) = sync_channel::<Box<int>>(0);
1887             spawn(proc() {
1888                 tx.send(box 10i);
1889             });
1890             spawn(proc() {
1891                 assert!(rx.recv() == box 10i);
1892             });
1893         }
1894     })
1895
1896     test!(fn stream_send_recv_stress() {
1897         for _ in range(0, stress_factor()) {
1898             let (tx, rx) = sync_channel::<Box<int>>(0);
1899
1900             send(tx, 0);
1901             recv(rx, 0);
1902
1903             fn send(tx: SyncSender<Box<int>>, i: int) {
1904                 if i == 10 { return }
1905
1906                 spawn(proc() {
1907                     tx.send(box i);
1908                     send(tx, i + 1);
1909                 });
1910             }
1911
1912             fn recv(rx: Receiver<Box<int>>, i: int) {
1913                 if i == 10 { return }
1914
1915                 spawn(proc() {
1916                     assert!(rx.recv() == box i);
1917                     recv(rx, i + 1);
1918                 });
1919             }
1920         }
1921     })
1922
1923     test!(fn recv_a_lot() {
1924         // Regression test that we don't run out of stack in scheduler context
1925         let (tx, rx) = sync_channel(10000);
1926         for _ in range(0u, 10000) { tx.send(()); }
1927         for _ in range(0u, 10000) { rx.recv(); }
1928     })
1929
1930     test!(fn shared_chan_stress() {
1931         let (tx, rx) = sync_channel(0);
1932         let total = stress_factor() + 100;
1933         for _ in range(0, total) {
1934             let tx = tx.clone();
1935             spawn(proc() {
1936                 tx.send(());
1937             });
1938         }
1939
1940         for _ in range(0, total) {
1941             rx.recv();
1942         }
1943     })
1944
1945     test!(fn test_nested_recv_iter() {
1946         let (tx, rx) = sync_channel::<int>(0);
1947         let (total_tx, total_rx) = sync_channel::<int>(0);
1948
1949         spawn(proc() {
1950             let mut acc = 0;
1951             for x in rx.iter() {
1952                 acc += x;
1953             }
1954             total_tx.send(acc);
1955         });
1956
1957         tx.send(3);
1958         tx.send(1);
1959         tx.send(2);
1960         drop(tx);
1961         assert_eq!(total_rx.recv(), 6);
1962     })
1963
1964     test!(fn test_recv_iter_break() {
1965         let (tx, rx) = sync_channel::<int>(0);
1966         let (count_tx, count_rx) = sync_channel(0);
1967
1968         spawn(proc() {
1969             let mut count = 0;
1970             for x in rx.iter() {
1971                 if count >= 3 {
1972                     break;
1973                 } else {
1974                     count += x;
1975                 }
1976             }
1977             count_tx.send(count);
1978         });
1979
1980         tx.send(2);
1981         tx.send(2);
1982         tx.send(2);
1983         let _ = tx.try_send(2);
1984         drop(tx);
1985         assert_eq!(count_rx.recv(), 4);
1986     })
1987
1988     test!(fn try_recv_states() {
1989         let (tx1, rx1) = sync_channel::<int>(1);
1990         let (tx2, rx2) = sync_channel::<()>(1);
1991         let (tx3, rx3) = sync_channel::<()>(1);
1992         spawn(proc() {
1993             rx2.recv();
1994             tx1.send(1);
1995             tx3.send(());
1996             rx2.recv();
1997             drop(tx1);
1998             tx3.send(());
1999         });
2000
2001         assert_eq!(rx1.try_recv(), Err(Empty));
2002         tx2.send(());
2003         rx3.recv();
2004         assert_eq!(rx1.try_recv(), Ok(1));
2005         assert_eq!(rx1.try_recv(), Err(Empty));
2006         tx2.send(());
2007         rx3.recv();
2008         assert_eq!(rx1.try_recv(), Err(Disconnected));
2009     })
2010
2011     // This bug used to end up in a livelock inside of the Receiver destructor
2012     // because the internal state of the Shared packet was corrupted
2013     test!(fn destroy_upgraded_shared_port_when_sender_still_active() {
2014         let (tx, rx) = sync_channel::<()>(0);
2015         let (tx2, rx2) = sync_channel::<()>(0);
2016         spawn(proc() {
2017             rx.recv(); // wait on a oneshot
2018             drop(rx);  // destroy a shared
2019             tx2.send(());
2020         });
2021         // make sure the other task has gone to sleep
2022         for _ in range(0u, 5000) { task::deschedule(); }
2023
2024         // upgrade to a shared chan and send a message
2025         let t = tx.clone();
2026         drop(tx);
2027         t.send(());
2028
2029         // wait for the child task to exit before we exit
2030         rx2.recv();
2031     })
2032
2033     test!(fn try_recvs_off_the_runtime() {
2034         use std::rt::thread::Thread;
2035
2036         let (tx, rx) = sync_channel::<()>(0);
2037         let (cdone, pdone) = channel();
2038         let t = Thread::start(proc() {
2039             let mut hits = 0u;
2040             while hits < 10 {
2041                 match rx.try_recv() {
2042                     Ok(()) => { hits += 1; }
2043                     Err(Empty) => { Thread::yield_now(); }
2044                     Err(Disconnected) => return,
2045                 }
2046             }
2047             cdone.send(());
2048         });
2049         for _ in range(0u, 10) {
2050             tx.send(());
2051         }
2052         t.join();
2053         pdone.recv();
2054     })
2055
2056     test!(fn send_opt1() {
2057         let (tx, rx) = sync_channel::<int>(0);
2058         spawn(proc() { rx.recv(); });
2059         assert_eq!(tx.send_opt(1), Ok(()));
2060     })
2061
2062     test!(fn send_opt2() {
2063         let (tx, rx) = sync_channel::<int>(0);
2064         spawn(proc() { drop(rx); });
2065         assert_eq!(tx.send_opt(1), Err(1));
2066     })
2067
2068     test!(fn send_opt3() {
2069         let (tx, rx) = sync_channel::<int>(1);
2070         assert_eq!(tx.send_opt(1), Ok(()));
2071         spawn(proc() { drop(rx); });
2072         assert_eq!(tx.send_opt(1), Err(1));
2073     })
2074
2075     test!(fn send_opt4() {
2076         let (tx, rx) = sync_channel::<int>(0);
2077         let tx2 = tx.clone();
2078         let (done, donerx) = channel();
2079         let done2 = done.clone();
2080         spawn(proc() {
2081             assert_eq!(tx.send_opt(1), Err(1));
2082             done.send(());
2083         });
2084         spawn(proc() {
2085             assert_eq!(tx2.send_opt(2), Err(2));
2086             done2.send(());
2087         });
2088         drop(rx);
2089         donerx.recv();
2090         donerx.recv();
2091     })
2092
2093     test!(fn try_send1() {
2094         let (tx, _rx) = sync_channel::<int>(0);
2095         assert_eq!(tx.try_send(1), Err(Full(1)));
2096     })
2097
2098     test!(fn try_send2() {
2099         let (tx, _rx) = sync_channel::<int>(1);
2100         assert_eq!(tx.try_send(1), Ok(()));
2101         assert_eq!(tx.try_send(1), Err(Full(1)));
2102     })
2103
2104     test!(fn try_send3() {
2105         let (tx, rx) = sync_channel::<int>(1);
2106         assert_eq!(tx.try_send(1), Ok(()));
2107         drop(rx);
2108         assert_eq!(tx.try_send(1), Err(RecvDisconnected(1)));
2109     })
2110
2111     test!(fn try_send4() {
2112         let (tx, rx) = sync_channel::<int>(0);
2113         spawn(proc() {
2114             for _ in range(0u, 1000) { task::deschedule(); }
2115             assert_eq!(tx.try_send(1), Ok(()));
2116         });
2117         assert_eq!(rx.recv(), 1);
2118     } #[ignore(reason = "flaky on libnative")])
2119
2120     test!(fn issue_15761() {
2121         fn repro() {
2122             let (tx1, rx1) = sync_channel::<()>(3);
2123             let (tx2, rx2) = sync_channel::<()>(3);
2124
2125             spawn(proc() {
2126                 rx1.recv();
2127                 tx2.try_send(()).unwrap();
2128             });
2129
2130             tx1.try_send(()).unwrap();
2131             rx2.recv();
2132         }
2133
2134         for _ in range(0u, 100) {
2135             repro()
2136         }
2137     })
2138 }