1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Multi-producer, single-consumer communication primitives threads
13 //! This module provides message-based communication over channels, concretely
14 //! defined among three types:
20 //! A `Sender` or `SyncSender` is used to send data to a `Receiver`. Both
21 //! senders are clone-able (multi-producer) such that many threads can send
22 //! simultaneously to one receiver (single-consumer).
24 //! These channels come in two flavors:
26 //! 1. An asynchronous, infinitely buffered channel. The `channel()` function
27 //! will return a `(Sender, Receiver)` tuple where all sends will be
28 //! **asynchronous** (they never block). The channel conceptually has an
31 //! 2. A synchronous, bounded channel. The `sync_channel()` function will return
32 //! a `(SyncSender, Receiver)` tuple where the storage for pending messages
33 //! is a pre-allocated buffer of a fixed size. All sends will be
34 //! **synchronous** by blocking until there is buffer space available. Note
35 //! that a bound of 0 is allowed, causing the channel to become a
36 //! "rendezvous" channel where each sender atomically hands off a message to
41 //! The send and receive operations on channels will all return a `Result`
42 //! indicating whether the operation succeeded or not. An unsuccessful operation
43 //! is normally indicative of the other half of a channel having "hung up" by
44 //! being dropped in its corresponding thread.
46 //! Once half of a channel has been deallocated, most operations can no longer
47 //! continue to make progress, so `Err` will be returned. Many applications will
48 //! continue to `unwrap()` the results returned from this module, instigating a
49 //! propagation of failure among threads if one unexpectedly dies.
56 //! use std::thread::Thread;
57 //! use std::sync::mpsc::channel;
59 //! // Create a simple streaming channel
60 //! let (tx, rx) = channel();
61 //! Thread::spawn(move|| {
62 //! tx.send(10i).unwrap();
64 //! assert_eq!(rx.recv().unwrap(), 10i);
70 //! use std::thread::Thread;
71 //! use std::sync::mpsc::channel;
73 //! // Create a shared channel that can be sent along from many threads
74 //! // where tx is the sending half (tx for transmission), and rx is the receiving
75 //! // half (rx for receiving).
76 //! let (tx, rx) = channel();
77 //! for i in range(0i, 10i) {
78 //! let tx = tx.clone();
79 //! Thread::spawn(move|| {
80 //! tx.send(i).unwrap();
84 //! for _ in range(0i, 10i) {
85 //! let j = rx.recv().unwrap();
86 //! assert!(0 <= j && j < 10);
90 //! Propagating panics:
93 //! use std::sync::mpsc::channel;
95 //! // The call to recv() will return an error because the channel has already
96 //! // hung up (or been deallocated)
97 //! let (tx, rx) = channel::<int>();
99 //! assert!(rx.recv().is_err());
102 //! Synchronous channels:
105 //! use std::thread::Thread;
106 //! use std::sync::mpsc::sync_channel;
108 //! let (tx, rx) = sync_channel::<int>(0);
109 //! Thread::spawn(move|| {
110 //! // This will wait for the parent task to start receiving
111 //! tx.send(53).unwrap();
113 //! rx.recv().unwrap();
116 //! Reading from a channel with a timeout requires to use a Timer together
117 //! with the channel. You can use the select! macro to select either and
118 //! handle the timeout case. This first example will break out of the loop
119 //! after 10 seconds no matter what:
122 //! use std::sync::mpsc::channel;
123 //! use std::io::timer::Timer;
124 //! use std::time::Duration;
126 //! let (tx, rx) = channel::<int>();
127 //! let mut timer = Timer::new().unwrap();
128 //! let timeout = timer.oneshot(Duration::seconds(10));
132 //! val = rx.recv() => println!("Received {}", val.unwrap()),
133 //! _ = timeout.recv() => {
134 //! println!("timed out, total time was more than 10 seconds");
141 //! This second example is more costly since it allocates a new timer every
142 //! time a message is received, but it allows you to timeout after the channel
143 //! has been inactive for 5 seconds:
146 //! use std::sync::mpsc::channel;
147 //! use std::io::timer::Timer;
148 //! use std::time::Duration;
150 //! let (tx, rx) = channel::<int>();
151 //! let mut timer = Timer::new().unwrap();
154 //! let timeout = timer.oneshot(Duration::seconds(5));
157 //! val = rx.recv() => println!("Received {}", val.unwrap()),
158 //! _ = timeout.recv() => {
159 //! println!("timed out, no message received in 5 seconds");
168 // A description of how Rust's channel implementation works
170 // Channels are supposed to be the basic building block for all other
171 // concurrent primitives that are used in Rust. As a result, the channel type
172 // needs to be highly optimized, flexible, and broad enough for use everywhere.
174 // The choice of implementation of all channels is to be built on lock-free data
175 // structures. The channels themselves are then consequently also lock-free data
176 // structures. As always with lock-free code, this is a very "here be dragons"
177 // territory, especially because I'm unaware of any academic papers that have
178 // gone into great length about channels of these flavors.
180 // ## Flavors of channels
182 // From the perspective of a consumer of this library, there is only one flavor
183 // of channel. This channel can be used as a stream and cloned to allow multiple
184 // senders. Under the hood, however, there are actually three flavors of
187 // * Flavor::Oneshots - these channels are highly optimized for the one-send use case.
188 // They contain as few atomics as possible and involve one and
189 // exactly one allocation.
190 // * Streams - these channels are optimized for the non-shared use case. They
191 // use a different concurrent queue that is more tailored for this
192 // use case. The initial allocation of this flavor of channel is not
194 // * Shared - this is the most general form of channel that this module offers,
195 // a channel with multiple senders. This type is as optimized as it
196 // can be, but the previous two types mentioned are much faster for
199 // ## Concurrent queues
201 // The basic idea of Rust's Sender/Receiver types is that send() never blocks, but
202 // recv() obviously blocks. This means that under the hood there must be some
203 // shared and concurrent queue holding all of the actual data.
205 // With two flavors of channels, two flavors of queues are also used. We have
206 // chosen to use queues from a well-known author that are abbreviated as SPSC
207 // and MPSC (single producer, single consumer and multiple producer, single
208 // consumer). SPSC queues are used for streams while MPSC queues are used for
211 // ### SPSC optimizations
213 // The SPSC queue found online is essentially a linked list of nodes where one
214 // half of the nodes are the "queue of data" and the other half of nodes are a
215 // cache of unused nodes. The unused nodes are used such that an allocation is
216 // not required on every push() and a free doesn't need to happen on every
219 // As found online, however, the cache of nodes is of an infinite size. This
220 // means that if a channel at one point in its life had 50k items in the queue,
221 // then the queue will always have the capacity for 50k items. I believed that
222 // this was an unnecessary limitation of the implementation, so I have altered
223 // the queue to optionally have a bound on the cache size.
225 // By default, streams will have an unbounded SPSC queue with a small-ish cache
226 // size. The hope is that the cache is still large enough to have very fast
227 // send() operations while not too large such that millions of channels can
230 // ### MPSC optimizations
232 // Right now the MPSC queue has not been optimized. Like the SPSC queue, it uses
233 // a linked list under the hood to earn its unboundedness, but I have not put
234 // forth much effort into having a cache of nodes similar to the SPSC queue.
236 // For now, I believe that this is "ok" because shared channels are not the most
237 // common type, but soon we may wish to revisit this queue choice and determine
238 // another candidate for backend storage of shared channels.
240 // ## Overview of the Implementation
242 // Now that there's a little background on the concurrent queues used, it's
243 // worth going into much more detail about the channels themselves. The basic
244 // pseudocode for a send/recv are:
248 // queue.push(t) return if queue.pop()
249 // if increment() == -1 deschedule {
250 // wakeup() if decrement() > 0
251 // cancel_deschedule()
255 // As mentioned before, there are no locks in this implementation, only atomic
256 // instructions are used.
258 // ### The internal atomic counter
260 // Every channel has a shared counter with each half to keep track of the size
261 // of the queue. This counter is used to abort descheduling by the receiver and
262 // to know when to wake up on the sending side.
264 // As seen in the pseudocode, senders will increment this count and receivers
265 // will decrement the count. The theory behind this is that if a sender sees a
266 // -1 count, it will wake up the receiver, and if the receiver sees a 1+ count,
267 // then it doesn't need to block.
269 // The recv() method has a beginning call to pop(), and if successful, it needs
270 // to decrement the count. It is a crucial implementation detail that this
271 // decrement does *not* happen to the shared counter. If this were the case,
272 // then it would be possible for the counter to be very negative when there were
273 // no receivers waiting, in which case the senders would have to determine when
274 // it was actually appropriate to wake up a receiver.
276 // Instead, the "steal count" is kept track of separately (not atomically
277 // because it's only used by receivers), and then the decrement() call when
278 // descheduling will lump in all of the recent steals into one large decrement.
280 // The implication of this is that if a sender sees a -1 count, then there's
281 // guaranteed to be a waiter waiting!
283 // ## Native Implementation
285 // A major goal of these channels is to work seamlessly on and off the runtime.
286 // All of the previous race conditions have been worded in terms of
287 // scheduler-isms (which is obviously not available without the runtime).
289 // For now, native usage of channels (off the runtime) will fall back onto
290 // mutexes/cond vars for descheduling/atomic decisions. The no-contention path
291 // is still entirely lock-free, the "deschedule" blocks above are surrounded by
292 // a mutex and the "wakeup" blocks involve grabbing a mutex and signaling on a
293 // condition variable.
297 // Being able to support selection over channels has greatly influenced this
298 // design, and not only does selection need to work inside the runtime, but also
299 // outside the runtime.
301 // The implementation is fairly straightforward. The goal of select() is not to
302 // return some data, but only to return which channel can receive data without
303 // blocking. The implementation is essentially the entire blocking procedure
304 // followed by an increment as soon as its woken up. The cancellation procedure
305 // involves an increment and swapping out of to_wake to acquire ownership of the
308 // Sadly this current implementation requires multiple allocations, so I have
309 // seen the throughput of select() be much worse than it should be. I do not
310 // believe that there is anything fundamental that needs to change about these
311 // channels, however, in order to support a more efficient select().
315 // And now that you've seen all the races that I found and attempted to fix,
316 // here's the code for you to find some more!
323 use cell::UnsafeCell;
325 pub use self::select::{Select, Handle};
326 use self::select::StartResult;
327 use self::select::StartResult::*;
328 use self::blocking::SignalToken;
339 /// The receiving-half of Rust's channel type. This half can only be owned by
342 pub struct Receiver<T> {
343 inner: UnsafeCell<Flavor<T>>,
346 // The receiver port can be sent from place to place, so long as it
347 // is not used to receive non-sendable things.
348 unsafe impl<T:Send> Send for Receiver<T> { }
350 /// An iterator over messages on a receiver, this iterator will block
351 /// whenever `next` is called, waiting for a new message, and `None` will be
352 /// returned when the corresponding channel has hung up.
354 pub struct Iter<'a, T:'a> {
358 /// The sending-half of Rust's asynchronous channel type. This half can only be
359 /// owned by one task, but it can be cloned to send to other tasks.
361 pub struct Sender<T> {
362 inner: UnsafeCell<Flavor<T>>,
365 // The send port can be sent from place to place, so long as it
366 // is not used to send non-sendable things.
367 unsafe impl<T:Send> Send for Sender<T> { }
369 /// The sending-half of Rust's synchronous channel type. This half can only be
370 /// owned by one task, but it can be cloned to send to other tasks.
372 pub struct SyncSender<T> {
373 inner: Arc<UnsafeCell<sync::Packet<T>>>,
376 unsafe impl<T:Send> Send for SyncSender<T> {}
378 impl<T> !Sync for SyncSender<T> {}
380 /// An error returned from the `send` function on channels.
382 /// A `send` operation can only fail if the receiving end of a channel is
383 /// disconnected, implying that the data could never be received. The error
384 /// contains the data being sent as a payload so it can be recovered.
385 #[derive(PartialEq, Eq, Show)]
387 pub struct SendError<T>(pub T);
389 /// An error returned from the `recv` function on a `Receiver`.
391 /// The `recv` operation can only fail if the sending half of a channel is
392 /// disconnected, implying that no further messages will ever be received.
393 #[derive(PartialEq, Eq, Clone, Copy, Show)]
395 pub struct RecvError;
397 /// This enumeration is the list of the possible reasons that try_recv could not
398 /// return data when called.
399 #[derive(PartialEq, Clone, Copy, Show)]
401 pub enum TryRecvError {
402 /// This channel is currently empty, but the sender(s) have not yet
403 /// disconnected, so data may yet become available.
407 /// This channel's sending half has become disconnected, and there will
408 /// never be any more data received on this channel
413 /// This enumeration is the list of the possible error outcomes for the
414 /// `SyncSender::try_send` method.
415 #[derive(PartialEq, Clone, Show)]
417 pub enum TrySendError<T> {
418 /// The data could not be sent on the channel because it would require that
419 /// the callee block to send the data.
421 /// If this is a buffered channel, then the buffer is full at this time. If
422 /// this is not a buffered channel, then there is no receiver available to
423 /// acquire the data.
427 /// This channel's receiving half has disconnected, so the data could not be
428 /// sent. The data is returned back to the callee in this case.
434 Oneshot(Arc<UnsafeCell<oneshot::Packet<T>>>),
435 Stream(Arc<UnsafeCell<stream::Packet<T>>>),
436 Shared(Arc<UnsafeCell<shared::Packet<T>>>),
437 Sync(Arc<UnsafeCell<sync::Packet<T>>>),
441 trait UnsafeFlavor<T> {
442 fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>>;
443 unsafe fn inner_mut<'a>(&'a self) -> &'a mut Flavor<T> {
444 &mut *self.inner_unsafe().get()
446 unsafe fn inner<'a>(&'a self) -> &'a Flavor<T> {
447 &*self.inner_unsafe().get()
450 impl<T> UnsafeFlavor<T> for Sender<T> {
451 fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> {
455 impl<T> UnsafeFlavor<T> for Receiver<T> {
456 fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> {
461 /// Creates a new asynchronous channel, returning the sender/receiver halves.
463 /// All data sent on the sender will become available on the receiver, and no
464 /// send will block the calling task (this channel has an "infinite buffer").
469 /// use std::sync::mpsc::channel;
470 /// use std::thread::Thread;
472 /// // tx is is the sending half (tx for transmission), and rx is the receiving
473 /// // half (rx for receiving).
474 /// let (tx, rx) = channel();
476 /// // Spawn off an expensive computation
477 /// Thread::spawn(move|| {
478 /// # fn expensive_computation() {}
479 /// tx.send(expensive_computation()).unwrap();
482 /// // Do some useful work for awhile
484 /// // Let's see what that answer was
485 /// println!("{:?}", rx.recv().unwrap());
488 pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) {
489 let a = Arc::new(UnsafeCell::new(oneshot::Packet::new()));
490 (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a)))
493 /// Creates a new synchronous, bounded channel.
495 /// Like asynchronous channels, the `Receiver` will block until a message
496 /// becomes available. These channels differ greatly in the semantics of the
497 /// sender from asynchronous channels, however.
499 /// This channel has an internal buffer on which messages will be queued. When
500 /// the internal buffer becomes full, future sends will *block* waiting for the
501 /// buffer to open up. Note that a buffer size of 0 is valid, in which case this
502 /// becomes "rendezvous channel" where each send will not return until a recv
503 /// is paired with it.
505 /// As with asynchronous channels, all senders will panic in `send` if the
506 /// `Receiver` has been destroyed.
511 /// use std::sync::mpsc::sync_channel;
512 /// use std::thread::Thread;
514 /// let (tx, rx) = sync_channel(1);
516 /// // this returns immediately
517 /// tx.send(1i).unwrap();
519 /// Thread::spawn(move|| {
520 /// // this will block until the previous message has been received
521 /// tx.send(2i).unwrap();
524 /// assert_eq!(rx.recv().unwrap(), 1i);
525 /// assert_eq!(rx.recv().unwrap(), 2i);
528 pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) {
529 let a = Arc::new(UnsafeCell::new(sync::Packet::new(bound)));
530 (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a)))
533 ////////////////////////////////////////////////////////////////////////////////
535 ////////////////////////////////////////////////////////////////////////////////
537 impl<T: Send> Sender<T> {
538 fn new(inner: Flavor<T>) -> Sender<T> {
540 inner: UnsafeCell::new(inner),
544 /// Attempts to send a value on this channel, returning it back if it could
547 /// A successful send occurs when it is determined that the other end of
548 /// the channel has not hung up already. An unsuccessful send would be one
549 /// where the corresponding receiver has already been deallocated. Note
550 /// that a return value of `Err` means that the data will never be
551 /// received, but a return value of `Ok` does *not* mean that the data
552 /// will be received. It is possible for the corresponding receiver to
553 /// hang up immediately after this function returns `Ok`.
555 /// This method will never block the current thread.
560 /// use std::sync::mpsc::channel;
562 /// let (tx, rx) = channel();
564 /// // This send is always successful
565 /// tx.send(1i).unwrap();
567 /// // This send will fail because the receiver is gone
569 /// assert_eq!(tx.send(1i).err().unwrap().0, 1);
572 pub fn send(&self, t: T) -> Result<(), SendError<T>> {
573 let (new_inner, ret) = match *unsafe { self.inner() } {
574 Flavor::Oneshot(ref p) => {
578 return (*p).send(t).map_err(SendError);
581 Arc::new(UnsafeCell::new(stream::Packet::new()));
582 let rx = Receiver::new(Flavor::Stream(a.clone()));
583 match (*p).upgrade(rx) {
584 oneshot::UpSuccess => {
585 let ret = (*a.get()).send(t);
588 oneshot::UpDisconnected => (a, Err(t)),
589 oneshot::UpWoke(token) => {
590 // This send cannot panic because the thread is
591 // asleep (we're looking at it), so the receiver
593 (*a.get()).send(t).ok().unwrap();
601 Flavor::Stream(ref p) => return unsafe {
602 (*p.get()).send(t).map_err(SendError)
604 Flavor::Shared(ref p) => return unsafe {
605 (*p.get()).send(t).map_err(SendError)
607 Flavor::Sync(..) => unreachable!(),
611 let tmp = Sender::new(Flavor::Stream(new_inner));
612 mem::swap(self.inner_mut(), tmp.inner_mut());
614 ret.map_err(SendError)
619 impl<T: Send> Clone for Sender<T> {
620 fn clone(&self) -> Sender<T> {
621 let (packet, sleeper, guard) = match *unsafe { self.inner() } {
622 Flavor::Oneshot(ref p) => {
623 let a = Arc::new(UnsafeCell::new(shared::Packet::new()));
625 let guard = (*a.get()).postinit_lock();
626 let rx = Receiver::new(Flavor::Shared(a.clone()));
627 match (*p.get()).upgrade(rx) {
629 oneshot::UpDisconnected => (a, None, guard),
630 oneshot::UpWoke(task) => (a, Some(task), guard)
634 Flavor::Stream(ref p) => {
635 let a = Arc::new(UnsafeCell::new(shared::Packet::new()));
637 let guard = (*a.get()).postinit_lock();
638 let rx = Receiver::new(Flavor::Shared(a.clone()));
639 match (*p.get()).upgrade(rx) {
641 stream::UpDisconnected => (a, None, guard),
642 stream::UpWoke(task) => (a, Some(task), guard),
646 Flavor::Shared(ref p) => {
647 unsafe { (*p.get()).clone_chan(); }
648 return Sender::new(Flavor::Shared(p.clone()));
650 Flavor::Sync(..) => unreachable!(),
654 (*packet.get()).inherit_blocker(sleeper, guard);
656 let tmp = Sender::new(Flavor::Shared(packet.clone()));
657 mem::swap(self.inner_mut(), tmp.inner_mut());
659 Sender::new(Flavor::Shared(packet))
665 impl<T: Send> Drop for Sender<T> {
667 match *unsafe { self.inner_mut() } {
668 Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); },
669 Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); },
670 Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); },
671 Flavor::Sync(..) => unreachable!(),
676 ////////////////////////////////////////////////////////////////////////////////
678 ////////////////////////////////////////////////////////////////////////////////
680 impl<T: Send> SyncSender<T> {
681 fn new(inner: Arc<UnsafeCell<sync::Packet<T>>>) -> SyncSender<T> {
682 SyncSender { inner: inner }
685 /// Sends a value on this synchronous channel.
687 /// This function will *block* until space in the internal buffer becomes
688 /// available or a receiver is available to hand off the message to.
690 /// Note that a successful send does *not* guarantee that the receiver will
691 /// ever see the data if there is a buffer on this channel. Items may be
692 /// enqueued in the internal buffer for the receiver to receive at a later
693 /// time. If the buffer size is 0, however, it can be guaranteed that the
694 /// receiver has indeed received the data if this function returns success.
696 /// This function will never panic, but it may return `Err` if the
697 /// `Receiver` has disconnected and is no longer able to receive
700 pub fn send(&self, t: T) -> Result<(), SendError<T>> {
701 unsafe { (*self.inner.get()).send(t).map_err(SendError) }
704 /// Attempts to send a value on this channel without blocking.
706 /// This method differs from `send` by returning immediately if the
707 /// channel's buffer is full or no receiver is waiting to acquire some
708 /// data. Compared with `send`, this function has two failure cases
709 /// instead of one (one for disconnection, one for a full buffer).
711 /// See `SyncSender::send` for notes about guarantees of whether the
712 /// receiver has received the data or not if this function is successful.
714 pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
715 unsafe { (*self.inner.get()).try_send(t) }
720 impl<T: Send> Clone for SyncSender<T> {
721 fn clone(&self) -> SyncSender<T> {
722 unsafe { (*self.inner.get()).clone_chan(); }
723 return SyncSender::new(self.inner.clone());
729 impl<T: Send> Drop for SyncSender<T> {
731 unsafe { (*self.inner.get()).drop_chan(); }
735 ////////////////////////////////////////////////////////////////////////////////
737 ////////////////////////////////////////////////////////////////////////////////
739 impl<T: Send> Receiver<T> {
740 fn new(inner: Flavor<T>) -> Receiver<T> {
741 Receiver { inner: UnsafeCell::new(inner) }
744 /// Attempts to return a pending value on this receiver without blocking
746 /// This method will never block the caller in order to wait for data to
747 /// become available. Instead, this will always return immediately with a
748 /// possible option of pending data on the channel.
750 /// This is useful for a flavor of "optimistic check" before deciding to
751 /// block on a receiver.
753 pub fn try_recv(&self) -> Result<T, TryRecvError> {
755 let new_port = match *unsafe { self.inner() } {
756 Flavor::Oneshot(ref p) => {
757 match unsafe { (*p.get()).try_recv() } {
758 Ok(t) => return Ok(t),
759 Err(oneshot::Empty) => return Err(TryRecvError::Empty),
760 Err(oneshot::Disconnected) => {
761 return Err(TryRecvError::Disconnected)
763 Err(oneshot::Upgraded(rx)) => rx,
766 Flavor::Stream(ref p) => {
767 match unsafe { (*p.get()).try_recv() } {
768 Ok(t) => return Ok(t),
769 Err(stream::Empty) => return Err(TryRecvError::Empty),
770 Err(stream::Disconnected) => {
771 return Err(TryRecvError::Disconnected)
773 Err(stream::Upgraded(rx)) => rx,
776 Flavor::Shared(ref p) => {
777 match unsafe { (*p.get()).try_recv() } {
778 Ok(t) => return Ok(t),
779 Err(shared::Empty) => return Err(TryRecvError::Empty),
780 Err(shared::Disconnected) => {
781 return Err(TryRecvError::Disconnected)
785 Flavor::Sync(ref p) => {
786 match unsafe { (*p.get()).try_recv() } {
787 Ok(t) => return Ok(t),
788 Err(sync::Empty) => return Err(TryRecvError::Empty),
789 Err(sync::Disconnected) => {
790 return Err(TryRecvError::Disconnected)
796 mem::swap(self.inner_mut(),
797 new_port.inner_mut());
802 /// Attempt to wait for a value on this receiver, returning an error if the
803 /// corresponding channel has hung up.
805 /// This function will always block the current thread if there is no data
806 /// available and it's possible for more data to be sent. Once a message is
807 /// sent to the corresponding `Sender`, then this receiver will wake up and
808 /// return that message.
810 /// If the corresponding `Sender` has disconnected, or it disconnects while
811 /// this call is blocking, this call will wake up and return `Err` to
812 /// indicate that no more messages can ever be received on this channel.
814 pub fn recv(&self) -> Result<T, RecvError> {
816 let new_port = match *unsafe { self.inner() } {
817 Flavor::Oneshot(ref p) => {
818 match unsafe { (*p.get()).recv() } {
819 Ok(t) => return Ok(t),
820 Err(oneshot::Empty) => return unreachable!(),
821 Err(oneshot::Disconnected) => return Err(RecvError),
822 Err(oneshot::Upgraded(rx)) => rx,
825 Flavor::Stream(ref p) => {
826 match unsafe { (*p.get()).recv() } {
827 Ok(t) => return Ok(t),
828 Err(stream::Empty) => return unreachable!(),
829 Err(stream::Disconnected) => return Err(RecvError),
830 Err(stream::Upgraded(rx)) => rx,
833 Flavor::Shared(ref p) => {
834 match unsafe { (*p.get()).recv() } {
835 Ok(t) => return Ok(t),
836 Err(shared::Empty) => return unreachable!(),
837 Err(shared::Disconnected) => return Err(RecvError),
840 Flavor::Sync(ref p) => return unsafe {
841 (*p.get()).recv().map_err(|()| RecvError)
845 mem::swap(self.inner_mut(), new_port.inner_mut());
850 /// Returns an iterator that will block waiting for messages, but never
851 /// `panic!`. It will return `None` when the channel has hung up.
853 pub fn iter(&self) -> Iter<T> {
858 impl<T: Send> select::Packet for Receiver<T> {
859 fn can_recv(&self) -> bool {
861 let new_port = match *unsafe { self.inner() } {
862 Flavor::Oneshot(ref p) => {
863 match unsafe { (*p.get()).can_recv() } {
864 Ok(ret) => return ret,
865 Err(upgrade) => upgrade,
868 Flavor::Stream(ref p) => {
869 match unsafe { (*p.get()).can_recv() } {
870 Ok(ret) => return ret,
871 Err(upgrade) => upgrade,
874 Flavor::Shared(ref p) => {
875 return unsafe { (*p.get()).can_recv() };
877 Flavor::Sync(ref p) => {
878 return unsafe { (*p.get()).can_recv() };
882 mem::swap(self.inner_mut(),
883 new_port.inner_mut());
888 fn start_selection(&self, mut token: SignalToken) -> StartResult {
890 let (t, new_port) = match *unsafe { self.inner() } {
891 Flavor::Oneshot(ref p) => {
892 match unsafe { (*p.get()).start_selection(token) } {
893 oneshot::SelSuccess => return Installed,
894 oneshot::SelCanceled => return Abort,
895 oneshot::SelUpgraded(t, rx) => (t, rx),
898 Flavor::Stream(ref p) => {
899 match unsafe { (*p.get()).start_selection(token) } {
900 stream::SelSuccess => return Installed,
901 stream::SelCanceled => return Abort,
902 stream::SelUpgraded(t, rx) => (t, rx),
905 Flavor::Shared(ref p) => {
906 return unsafe { (*p.get()).start_selection(token) };
908 Flavor::Sync(ref p) => {
909 return unsafe { (*p.get()).start_selection(token) };
914 mem::swap(self.inner_mut(), new_port.inner_mut());
919 fn abort_selection(&self) -> bool {
920 let mut was_upgrade = false;
922 let result = match *unsafe { self.inner() } {
923 Flavor::Oneshot(ref p) => unsafe { (*p.get()).abort_selection() },
924 Flavor::Stream(ref p) => unsafe {
925 (*p.get()).abort_selection(was_upgrade)
927 Flavor::Shared(ref p) => return unsafe {
928 (*p.get()).abort_selection(was_upgrade)
930 Flavor::Sync(ref p) => return unsafe {
931 (*p.get()).abort_selection()
934 let new_port = match result { Ok(b) => return b, Err(p) => p };
937 mem::swap(self.inner_mut(),
938 new_port.inner_mut());
945 impl<'a, T: Send> Iterator for Iter<'a, T> {
948 fn next(&mut self) -> Option<T> { self.rx.recv().ok() }
953 impl<T: Send> Drop for Receiver<T> {
955 match *unsafe { self.inner_mut() } {
956 Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); },
957 Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_port(); },
958 Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_port(); },
959 Flavor::Sync(ref mut p) => unsafe { (*p.get()).drop_port(); },
965 impl<T> fmt::Display for SendError<T> {
966 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
967 "sending on a closed channel".fmt(f)
972 impl<T> fmt::Display for TrySendError<T> {
973 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
975 TrySendError::Full(..) => {
976 "sending on a full channel".fmt(f)
978 TrySendError::Disconnected(..) => {
979 "sending on a closed channel".fmt(f)
986 impl fmt::Display for RecvError {
987 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
988 "receiving on a closed channel".fmt(f)
993 impl fmt::Display for TryRecvError {
994 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
996 TryRecvError::Empty => {
997 "receiving on an empty channel".fmt(f)
999 TryRecvError::Disconnected => {
1000 "receiving on a closed channel".fmt(f)
1014 pub fn stress_factor() -> uint {
1015 match os::getenv("RUST_TEST_STRESS") {
1016 Some(val) => val.parse().unwrap(),
1023 let (tx, rx) = channel::<int>();
1024 tx.send(1).unwrap();
1025 assert_eq!(rx.recv().unwrap(), 1);
1030 let (tx, _rx) = channel();
1031 tx.send(box 1i).unwrap();
1035 fn drop_full_shared() {
1036 let (tx, _rx) = channel();
1039 tx.send(box 1i).unwrap();
1044 let (tx, rx) = channel::<int>();
1045 tx.send(1).unwrap();
1046 assert_eq!(rx.recv().unwrap(), 1);
1047 let tx = tx.clone();
1048 tx.send(1).unwrap();
1049 assert_eq!(rx.recv().unwrap(), 1);
1053 fn smoke_threads() {
1054 let (tx, rx) = channel::<int>();
1055 let _t = Thread::spawn(move|| {
1056 tx.send(1).unwrap();
1058 assert_eq!(rx.recv().unwrap(), 1);
1062 fn smoke_port_gone() {
1063 let (tx, rx) = channel::<int>();
1065 assert!(tx.send(1).is_err());
1069 fn smoke_shared_port_gone() {
1070 let (tx, rx) = channel::<int>();
1072 assert!(tx.send(1).is_err())
1076 fn smoke_shared_port_gone2() {
1077 let (tx, rx) = channel::<int>();
1079 let tx2 = tx.clone();
1081 assert!(tx2.send(1).is_err());
1085 fn port_gone_concurrent() {
1086 let (tx, rx) = channel::<int>();
1087 let _t = Thread::spawn(move|| {
1090 while tx.send(1).is_ok() {}
1094 fn port_gone_concurrent_shared() {
1095 let (tx, rx) = channel::<int>();
1096 let tx2 = tx.clone();
1097 let _t = Thread::spawn(move|| {
1100 while tx.send(1).is_ok() && tx2.send(1).is_ok() {}
1104 fn smoke_chan_gone() {
1105 let (tx, rx) = channel::<int>();
1107 assert!(rx.recv().is_err());
1111 fn smoke_chan_gone_shared() {
1112 let (tx, rx) = channel::<()>();
1113 let tx2 = tx.clone();
1116 assert!(rx.recv().is_err());
1120 fn chan_gone_concurrent() {
1121 let (tx, rx) = channel::<int>();
1122 let _t = Thread::spawn(move|| {
1123 tx.send(1).unwrap();
1124 tx.send(1).unwrap();
1126 while rx.recv().is_ok() {}
1131 let (tx, rx) = channel::<int>();
1132 let t = Thread::scoped(move|| {
1133 for _ in range(0u, 10000) { tx.send(1i).unwrap(); }
1135 for _ in range(0u, 10000) {
1136 assert_eq!(rx.recv().unwrap(), 1);
1138 t.join().ok().unwrap();
1142 fn stress_shared() {
1143 static AMT: uint = 10000;
1144 static NTHREADS: uint = 8;
1145 let (tx, rx) = channel::<int>();
1147 let t = Thread::scoped(move|| {
1148 for _ in range(0, AMT * NTHREADS) {
1149 assert_eq!(rx.recv().unwrap(), 1);
1151 match rx.try_recv() {
1157 for _ in range(0, NTHREADS) {
1158 let tx = tx.clone();
1159 Thread::spawn(move|| {
1160 for _ in range(0, AMT) { tx.send(1).unwrap(); }
1164 t.join().ok().unwrap();
1168 fn send_from_outside_runtime() {
1169 let (tx1, rx1) = channel::<()>();
1170 let (tx2, rx2) = channel::<int>();
1171 let t1 = Thread::scoped(move|| {
1172 tx1.send(()).unwrap();
1173 for _ in range(0i, 40) {
1174 assert_eq!(rx2.recv().unwrap(), 1);
1177 rx1.recv().unwrap();
1178 let t2 = Thread::scoped(move|| {
1179 for _ in range(0i, 40) {
1180 tx2.send(1).unwrap();
1183 t1.join().ok().unwrap();
1184 t2.join().ok().unwrap();
1188 fn recv_from_outside_runtime() {
1189 let (tx, rx) = channel::<int>();
1190 let t = Thread::scoped(move|| {
1191 for _ in range(0i, 40) {
1192 assert_eq!(rx.recv().unwrap(), 1);
1195 for _ in range(0u, 40) {
1196 tx.send(1).unwrap();
1198 t.join().ok().unwrap();
1203 let (tx1, rx1) = channel::<int>();
1204 let (tx2, rx2) = channel::<int>();
1205 let t1 = Thread::scoped(move|| {
1206 assert_eq!(rx1.recv().unwrap(), 1);
1207 tx2.send(2).unwrap();
1209 let t2 = Thread::scoped(move|| {
1210 tx1.send(1).unwrap();
1211 assert_eq!(rx2.recv().unwrap(), 2);
1213 t1.join().ok().unwrap();
1214 t2.join().ok().unwrap();
1218 fn oneshot_single_thread_close_port_first() {
1219 // Simple test of closing without sending
1220 let (_tx, rx) = channel::<int>();
1225 fn oneshot_single_thread_close_chan_first() {
1226 // Simple test of closing without sending
1227 let (tx, _rx) = channel::<int>();
1232 fn oneshot_single_thread_send_port_close() {
1233 // Testing that the sender cleans up the payload if receiver is closed
1234 let (tx, rx) = channel::<Box<int>>();
1236 assert!(tx.send(box 0).is_err());
1240 fn oneshot_single_thread_recv_chan_close() {
1241 // Receiving on a closed chan will panic
1242 let res = Thread::scoped(move|| {
1243 let (tx, rx) = channel::<int>();
1248 assert!(res.is_err());
1252 fn oneshot_single_thread_send_then_recv() {
1253 let (tx, rx) = channel::<Box<int>>();
1254 tx.send(box 10).unwrap();
1255 assert!(rx.recv().unwrap() == box 10);
1259 fn oneshot_single_thread_try_send_open() {
1260 let (tx, rx) = channel::<int>();
1261 assert!(tx.send(10).is_ok());
1262 assert!(rx.recv().unwrap() == 10);
1266 fn oneshot_single_thread_try_send_closed() {
1267 let (tx, rx) = channel::<int>();
1269 assert!(tx.send(10).is_err());
1273 fn oneshot_single_thread_try_recv_open() {
1274 let (tx, rx) = channel::<int>();
1275 tx.send(10).unwrap();
1276 assert!(rx.recv() == Ok(10));
1280 fn oneshot_single_thread_try_recv_closed() {
1281 let (tx, rx) = channel::<int>();
1283 assert!(rx.recv().is_err());
1287 fn oneshot_single_thread_peek_data() {
1288 let (tx, rx) = channel::<int>();
1289 assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
1290 tx.send(10).unwrap();
1291 assert_eq!(rx.try_recv(), Ok(10));
1295 fn oneshot_single_thread_peek_close() {
1296 let (tx, rx) = channel::<int>();
1298 assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected));
1299 assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected));
1303 fn oneshot_single_thread_peek_open() {
1304 let (_tx, rx) = channel::<int>();
1305 assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
1309 fn oneshot_multi_task_recv_then_send() {
1310 let (tx, rx) = channel::<Box<int>>();
1311 let _t = Thread::spawn(move|| {
1312 assert!(rx.recv().unwrap() == box 10);
1315 tx.send(box 10).unwrap();
1319 fn oneshot_multi_task_recv_then_close() {
1320 let (tx, rx) = channel::<Box<int>>();
1321 let _t = Thread::spawn(move|| {
1324 let res = Thread::scoped(move|| {
1325 assert!(rx.recv().unwrap() == box 10);
1327 assert!(res.is_err());
1331 fn oneshot_multi_thread_close_stress() {
1332 for _ in range(0, stress_factor()) {
1333 let (tx, rx) = channel::<int>();
1334 let _t = Thread::spawn(move|| {
1342 fn oneshot_multi_thread_send_close_stress() {
1343 for _ in range(0, stress_factor()) {
1344 let (tx, rx) = channel::<int>();
1345 let _t = Thread::spawn(move|| {
1348 let _ = Thread::scoped(move|| {
1349 tx.send(1).unwrap();
1355 fn oneshot_multi_thread_recv_close_stress() {
1356 for _ in range(0, stress_factor()) {
1357 let (tx, rx) = channel::<int>();
1358 Thread::spawn(move|| {
1359 let res = Thread::scoped(move|| {
1362 assert!(res.is_err());
1364 let _t = Thread::spawn(move|| {
1365 Thread::spawn(move|| {
1373 fn oneshot_multi_thread_send_recv_stress() {
1374 for _ in range(0, stress_factor()) {
1375 let (tx, rx) = channel();
1376 let _t = Thread::spawn(move|| {
1377 tx.send(box 10i).unwrap();
1379 assert!(rx.recv().unwrap() == box 10i);
1384 fn stream_send_recv_stress() {
1385 for _ in range(0, stress_factor()) {
1386 let (tx, rx) = channel();
1391 fn send(tx: Sender<Box<int>>, i: int) {
1392 if i == 10 { return }
1394 Thread::spawn(move|| {
1395 tx.send(box i).unwrap();
1400 fn recv(rx: Receiver<Box<int>>, i: int) {
1401 if i == 10 { return }
1403 Thread::spawn(move|| {
1404 assert!(rx.recv().unwrap() == box i);
1413 // Regression test that we don't run out of stack in scheduler context
1414 let (tx, rx) = channel();
1415 for _ in range(0i, 10000) { tx.send(()).unwrap(); }
1416 for _ in range(0i, 10000) { rx.recv().unwrap(); }
1420 fn shared_chan_stress() {
1421 let (tx, rx) = channel();
1422 let total = stress_factor() + 100;
1423 for _ in range(0, total) {
1424 let tx = tx.clone();
1425 Thread::spawn(move|| {
1426 tx.send(()).unwrap();
1430 for _ in range(0, total) {
1436 fn test_nested_recv_iter() {
1437 let (tx, rx) = channel::<int>();
1438 let (total_tx, total_rx) = channel::<int>();
1440 let _t = Thread::spawn(move|| {
1442 for x in rx.iter() {
1445 total_tx.send(acc).unwrap();
1448 tx.send(3).unwrap();
1449 tx.send(1).unwrap();
1450 tx.send(2).unwrap();
1452 assert_eq!(total_rx.recv().unwrap(), 6);
1456 fn test_recv_iter_break() {
1457 let (tx, rx) = channel::<int>();
1458 let (count_tx, count_rx) = channel();
1460 let _t = Thread::spawn(move|| {
1462 for x in rx.iter() {
1469 count_tx.send(count).unwrap();
1472 tx.send(2).unwrap();
1473 tx.send(2).unwrap();
1474 tx.send(2).unwrap();
1477 assert_eq!(count_rx.recv().unwrap(), 4);
1481 fn try_recv_states() {
1482 let (tx1, rx1) = channel::<int>();
1483 let (tx2, rx2) = channel::<()>();
1484 let (tx3, rx3) = channel::<()>();
1485 let _t = Thread::spawn(move|| {
1486 rx2.recv().unwrap();
1487 tx1.send(1).unwrap();
1488 tx3.send(()).unwrap();
1489 rx2.recv().unwrap();
1491 tx3.send(()).unwrap();
1494 assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
1495 tx2.send(()).unwrap();
1496 rx3.recv().unwrap();
1497 assert_eq!(rx1.try_recv(), Ok(1));
1498 assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
1499 tx2.send(()).unwrap();
1500 rx3.recv().unwrap();
1501 assert_eq!(rx1.try_recv(), Err(TryRecvError::Disconnected));
1504 // This bug used to end up in a livelock inside of the Receiver destructor
1505 // because the internal state of the Shared packet was corrupted
1507 fn destroy_upgraded_shared_port_when_sender_still_active() {
1508 let (tx, rx) = channel();
1509 let (tx2, rx2) = channel();
1510 let _t = Thread::spawn(move|| {
1511 rx.recv().unwrap(); // wait on a oneshot
1512 drop(rx); // destroy a shared
1513 tx2.send(()).unwrap();
1515 // make sure the other task has gone to sleep
1516 for _ in range(0u, 5000) { Thread::yield_now(); }
1518 // upgrade to a shared chan and send a message
1521 t.send(()).unwrap();
1523 // wait for the child task to exit before we exit
1524 rx2.recv().unwrap();
1536 pub fn stress_factor() -> uint {
1537 match os::getenv("RUST_TEST_STRESS") {
1538 Some(val) => val.parse().unwrap(),
1545 let (tx, rx) = sync_channel::<int>(1);
1546 tx.send(1).unwrap();
1547 assert_eq!(rx.recv().unwrap(), 1);
1552 let (tx, _rx) = sync_channel(1);
1553 tx.send(box 1i).unwrap();
1558 let (tx, rx) = sync_channel::<int>(1);
1559 tx.send(1).unwrap();
1560 assert_eq!(rx.recv().unwrap(), 1);
1561 let tx = tx.clone();
1562 tx.send(1).unwrap();
1563 assert_eq!(rx.recv().unwrap(), 1);
1567 fn smoke_threads() {
1568 let (tx, rx) = sync_channel::<int>(0);
1569 let _t = Thread::spawn(move|| {
1570 tx.send(1).unwrap();
1572 assert_eq!(rx.recv().unwrap(), 1);
1576 fn smoke_port_gone() {
1577 let (tx, rx) = sync_channel::<int>(0);
1579 assert!(tx.send(1).is_err());
1583 fn smoke_shared_port_gone2() {
1584 let (tx, rx) = sync_channel::<int>(0);
1586 let tx2 = tx.clone();
1588 assert!(tx2.send(1).is_err());
1592 fn port_gone_concurrent() {
1593 let (tx, rx) = sync_channel::<int>(0);
1594 let _t = Thread::spawn(move|| {
1597 while tx.send(1).is_ok() {}
1601 fn port_gone_concurrent_shared() {
1602 let (tx, rx) = sync_channel::<int>(0);
1603 let tx2 = tx.clone();
1604 let _t = Thread::spawn(move|| {
1607 while tx.send(1).is_ok() && tx2.send(1).is_ok() {}
1611 fn smoke_chan_gone() {
1612 let (tx, rx) = sync_channel::<int>(0);
1614 assert!(rx.recv().is_err());
1618 fn smoke_chan_gone_shared() {
1619 let (tx, rx) = sync_channel::<()>(0);
1620 let tx2 = tx.clone();
1623 assert!(rx.recv().is_err());
1627 fn chan_gone_concurrent() {
1628 let (tx, rx) = sync_channel::<int>(0);
1629 Thread::spawn(move|| {
1630 tx.send(1).unwrap();
1631 tx.send(1).unwrap();
1633 while rx.recv().is_ok() {}
1638 let (tx, rx) = sync_channel::<int>(0);
1639 Thread::spawn(move|| {
1640 for _ in range(0u, 10000) { tx.send(1).unwrap(); }
1642 for _ in range(0u, 10000) {
1643 assert_eq!(rx.recv().unwrap(), 1);
1648 fn stress_shared() {
1649 static AMT: uint = 1000;
1650 static NTHREADS: uint = 8;
1651 let (tx, rx) = sync_channel::<int>(0);
1652 let (dtx, drx) = sync_channel::<()>(0);
1654 Thread::spawn(move|| {
1655 for _ in range(0, AMT * NTHREADS) {
1656 assert_eq!(rx.recv().unwrap(), 1);
1658 match rx.try_recv() {
1662 dtx.send(()).unwrap();
1665 for _ in range(0, NTHREADS) {
1666 let tx = tx.clone();
1667 Thread::spawn(move|| {
1668 for _ in range(0, AMT) { tx.send(1).unwrap(); }
1672 drx.recv().unwrap();
1676 fn oneshot_single_thread_close_port_first() {
1677 // Simple test of closing without sending
1678 let (_tx, rx) = sync_channel::<int>(0);
1683 fn oneshot_single_thread_close_chan_first() {
1684 // Simple test of closing without sending
1685 let (tx, _rx) = sync_channel::<int>(0);
1690 fn oneshot_single_thread_send_port_close() {
1691 // Testing that the sender cleans up the payload if receiver is closed
1692 let (tx, rx) = sync_channel::<Box<int>>(0);
1694 assert!(tx.send(box 0).is_err());
1698 fn oneshot_single_thread_recv_chan_close() {
1699 // Receiving on a closed chan will panic
1700 let res = Thread::scoped(move|| {
1701 let (tx, rx) = sync_channel::<int>(0);
1706 assert!(res.is_err());
1710 fn oneshot_single_thread_send_then_recv() {
1711 let (tx, rx) = sync_channel::<Box<int>>(1);
1712 tx.send(box 10).unwrap();
1713 assert!(rx.recv().unwrap() == box 10);
1717 fn oneshot_single_thread_try_send_open() {
1718 let (tx, rx) = sync_channel::<int>(1);
1719 assert_eq!(tx.try_send(10), Ok(()));
1720 assert!(rx.recv().unwrap() == 10);
1724 fn oneshot_single_thread_try_send_closed() {
1725 let (tx, rx) = sync_channel::<int>(0);
1727 assert_eq!(tx.try_send(10), Err(TrySendError::Disconnected(10)));
1731 fn oneshot_single_thread_try_send_closed2() {
1732 let (tx, _rx) = sync_channel::<int>(0);
1733 assert_eq!(tx.try_send(10), Err(TrySendError::Full(10)));
1737 fn oneshot_single_thread_try_recv_open() {
1738 let (tx, rx) = sync_channel::<int>(1);
1739 tx.send(10).unwrap();
1740 assert!(rx.recv() == Ok(10));
1744 fn oneshot_single_thread_try_recv_closed() {
1745 let (tx, rx) = sync_channel::<int>(0);
1747 assert!(rx.recv().is_err());
1751 fn oneshot_single_thread_peek_data() {
1752 let (tx, rx) = sync_channel::<int>(1);
1753 assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
1754 tx.send(10).unwrap();
1755 assert_eq!(rx.try_recv(), Ok(10));
1759 fn oneshot_single_thread_peek_close() {
1760 let (tx, rx) = sync_channel::<int>(0);
1762 assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected));
1763 assert_eq!(rx.try_recv(), Err(TryRecvError::Disconnected));
1767 fn oneshot_single_thread_peek_open() {
1768 let (_tx, rx) = sync_channel::<int>(0);
1769 assert_eq!(rx.try_recv(), Err(TryRecvError::Empty));
1773 fn oneshot_multi_task_recv_then_send() {
1774 let (tx, rx) = sync_channel::<Box<int>>(0);
1775 let _t = Thread::spawn(move|| {
1776 assert!(rx.recv().unwrap() == box 10);
1779 tx.send(box 10).unwrap();
1783 fn oneshot_multi_task_recv_then_close() {
1784 let (tx, rx) = sync_channel::<Box<int>>(0);
1785 let _t = Thread::spawn(move|| {
1788 let res = Thread::scoped(move|| {
1789 assert!(rx.recv().unwrap() == box 10);
1791 assert!(res.is_err());
1795 fn oneshot_multi_thread_close_stress() {
1796 for _ in range(0, stress_factor()) {
1797 let (tx, rx) = sync_channel::<int>(0);
1798 let _t = Thread::spawn(move|| {
1806 fn oneshot_multi_thread_send_close_stress() {
1807 for _ in range(0, stress_factor()) {
1808 let (tx, rx) = sync_channel::<int>(0);
1809 let _t = Thread::spawn(move|| {
1812 let _ = Thread::scoped(move || {
1813 tx.send(1).unwrap();
1819 fn oneshot_multi_thread_recv_close_stress() {
1820 for _ in range(0, stress_factor()) {
1821 let (tx, rx) = sync_channel::<int>(0);
1822 let _t = Thread::spawn(move|| {
1823 let res = Thread::scoped(move|| {
1826 assert!(res.is_err());
1828 let _t = Thread::spawn(move|| {
1829 Thread::spawn(move|| {
1837 fn oneshot_multi_thread_send_recv_stress() {
1838 for _ in range(0, stress_factor()) {
1839 let (tx, rx) = sync_channel::<Box<int>>(0);
1840 let _t = Thread::spawn(move|| {
1841 tx.send(box 10i).unwrap();
1843 assert!(rx.recv().unwrap() == box 10i);
1848 fn stream_send_recv_stress() {
1849 for _ in range(0, stress_factor()) {
1850 let (tx, rx) = sync_channel::<Box<int>>(0);
1855 fn send(tx: SyncSender<Box<int>>, i: int) {
1856 if i == 10 { return }
1858 Thread::spawn(move|| {
1859 tx.send(box i).unwrap();
1864 fn recv(rx: Receiver<Box<int>>, i: int) {
1865 if i == 10 { return }
1867 Thread::spawn(move|| {
1868 assert!(rx.recv().unwrap() == box i);
1877 // Regression test that we don't run out of stack in scheduler context
1878 let (tx, rx) = sync_channel(10000);
1879 for _ in range(0u, 10000) { tx.send(()).unwrap(); }
1880 for _ in range(0u, 10000) { rx.recv().unwrap(); }
1884 fn shared_chan_stress() {
1885 let (tx, rx) = sync_channel(0);
1886 let total = stress_factor() + 100;
1887 for _ in range(0, total) {
1888 let tx = tx.clone();
1889 Thread::spawn(move|| {
1890 tx.send(()).unwrap();
1894 for _ in range(0, total) {
1900 fn test_nested_recv_iter() {
1901 let (tx, rx) = sync_channel::<int>(0);
1902 let (total_tx, total_rx) = sync_channel::<int>(0);
1904 let _t = Thread::spawn(move|| {
1906 for x in rx.iter() {
1909 total_tx.send(acc).unwrap();
1912 tx.send(3).unwrap();
1913 tx.send(1).unwrap();
1914 tx.send(2).unwrap();
1916 assert_eq!(total_rx.recv().unwrap(), 6);
1920 fn test_recv_iter_break() {
1921 let (tx, rx) = sync_channel::<int>(0);
1922 let (count_tx, count_rx) = sync_channel(0);
1924 let _t = Thread::spawn(move|| {
1926 for x in rx.iter() {
1933 count_tx.send(count).unwrap();
1936 tx.send(2).unwrap();
1937 tx.send(2).unwrap();
1938 tx.send(2).unwrap();
1939 let _ = tx.try_send(2);
1941 assert_eq!(count_rx.recv().unwrap(), 4);
1945 fn try_recv_states() {
1946 let (tx1, rx1) = sync_channel::<int>(1);
1947 let (tx2, rx2) = sync_channel::<()>(1);
1948 let (tx3, rx3) = sync_channel::<()>(1);
1949 let _t = Thread::spawn(move|| {
1950 rx2.recv().unwrap();
1951 tx1.send(1).unwrap();
1952 tx3.send(()).unwrap();
1953 rx2.recv().unwrap();
1955 tx3.send(()).unwrap();
1958 assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
1959 tx2.send(()).unwrap();
1960 rx3.recv().unwrap();
1961 assert_eq!(rx1.try_recv(), Ok(1));
1962 assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty));
1963 tx2.send(()).unwrap();
1964 rx3.recv().unwrap();
1965 assert_eq!(rx1.try_recv(), Err(TryRecvError::Disconnected));
1968 // This bug used to end up in a livelock inside of the Receiver destructor
1969 // because the internal state of the Shared packet was corrupted
1971 fn destroy_upgraded_shared_port_when_sender_still_active() {
1972 let (tx, rx) = sync_channel::<()>(0);
1973 let (tx2, rx2) = sync_channel::<()>(0);
1974 let _t = Thread::spawn(move|| {
1975 rx.recv().unwrap(); // wait on a oneshot
1976 drop(rx); // destroy a shared
1977 tx2.send(()).unwrap();
1979 // make sure the other task has gone to sleep
1980 for _ in range(0u, 5000) { Thread::yield_now(); }
1982 // upgrade to a shared chan and send a message
1985 t.send(()).unwrap();
1987 // wait for the child task to exit before we exit
1988 rx2.recv().unwrap();
1993 let (tx, rx) = sync_channel::<int>(0);
1994 let _t = Thread::spawn(move|| { rx.recv().unwrap(); });
1995 assert_eq!(tx.send(1), Ok(()));
2000 let (tx, rx) = sync_channel::<int>(0);
2001 let _t = Thread::spawn(move|| { drop(rx); });
2002 assert!(tx.send(1).is_err());
2007 let (tx, rx) = sync_channel::<int>(1);
2008 assert_eq!(tx.send(1), Ok(()));
2009 let _t =Thread::spawn(move|| { drop(rx); });
2010 assert!(tx.send(1).is_err());
2015 let (tx, rx) = sync_channel::<int>(0);
2016 let tx2 = tx.clone();
2017 let (done, donerx) = channel();
2018 let done2 = done.clone();
2019 let _t = Thread::spawn(move|| {
2020 assert!(tx.send(1).is_err());
2021 done.send(()).unwrap();
2023 let _t = Thread::spawn(move|| {
2024 assert!(tx2.send(2).is_err());
2025 done2.send(()).unwrap();
2028 donerx.recv().unwrap();
2029 donerx.recv().unwrap();
2034 let (tx, _rx) = sync_channel::<int>(0);
2035 assert_eq!(tx.try_send(1), Err(TrySendError::Full(1)));
2040 let (tx, _rx) = sync_channel::<int>(1);
2041 assert_eq!(tx.try_send(1), Ok(()));
2042 assert_eq!(tx.try_send(1), Err(TrySendError::Full(1)));
2047 let (tx, rx) = sync_channel::<int>(1);
2048 assert_eq!(tx.try_send(1), Ok(()));
2050 assert_eq!(tx.try_send(1), Err(TrySendError::Disconnected(1)));
2056 let (tx1, rx1) = sync_channel::<()>(3);
2057 let (tx2, rx2) = sync_channel::<()>(3);
2059 let _t = Thread::spawn(move|| {
2060 rx1.recv().unwrap();
2061 tx2.try_send(()).unwrap();
2064 tx1.try_send(()).unwrap();
2065 rx2.recv().unwrap();
2068 for _ in range(0u, 100) {