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 //! Communication primitives for concurrent tasks
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.
18 //! This module provides message-based communication over channels, concretely
19 //! defined among three types:
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
31 //! Rust channels come in one of two flavors:
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
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
46 //! ## Failure Propagation
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.
54 //! There are methods on both of senders and receivers to perform their
55 //! respective operations without failing, however.
57 //! ## Runtime Requirements
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.
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.
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.
77 //! // Create a simple streaming channel
78 //! let (tx, rx) = channel();
82 //! assert_eq!(rx.recv(), 10i);
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();
99 //! for _ in range(0i, 10i) {
100 //! let j = rx.recv();
101 //! assert!(0 <= j && j < 10);
105 //! Propagating failure:
108 //! // The call to recv() will fail!() because the channel has already hung
109 //! // up (or been deallocated)
110 //! let (tx, rx) = channel::<int>();
115 //! Synchronous channels:
118 //! let (tx, rx) = sync_channel::<int>(0);
120 //! // This will wait for the parent task to start receiving
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:
132 //! use std::io::timer::Timer;
133 //! use std::time::Duration;
135 //! let (tx, rx) = channel::<int>();
136 //! let mut timer = Timer::new().unwrap();
137 //! let timeout = timer.oneshot(Duration::seconds(10));
141 //! val = rx.recv() => println!("Received {}", val),
142 //! () = timeout.recv() => {
143 //! println!("timed out, total time was more than 10 seconds")
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:
155 //! use std::io::timer::Timer;
156 //! use std::time::Duration;
158 //! let (tx, rx) = channel::<int>();
159 //! let mut timer = Timer::new().unwrap();
162 //! let timeout = timer.oneshot(Duration::seconds(5));
165 //! val = rx.recv() => println!("Received {}", val),
166 //! () = timeout.recv() => {
167 //! println!("timed out, no message received in 5 seconds")
174 // A description of how Rust's channel implementation works
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.
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.
186 // ## Flavors of channels
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
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
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
205 // ## Concurrent queues
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.
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
217 // ### SPSC optimizations
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
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.
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
236 // ### MPSC optimizations
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.
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.
246 // ## Overview of the Implementation
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:
254 // queue.push(t) return if queue.pop()
255 // if increment() == -1 deschedule {
256 // wakeup() if decrement() > 0
257 // cancel_deschedule()
261 // As mentioned before, there are no locks in this implementation, only atomic
262 // instructions are used.
264 // ### The internal atomic counter
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.
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.
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.
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.
286 // The implication of this is that if a sender sees a -1 count, then there's
287 // guaranteed to be a waiter waiting!
289 // ## Native Implementation
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).
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.
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.
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
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().
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!
324 use core::prelude::*;
327 use alloc::boxed::Box;
328 use core::cell::Cell;
329 use core::kinds::marker;
331 use core::cell::UnsafeCell;
332 use rustrt::local::Local;
333 use rustrt::task::{Task, BlockedTask};
335 pub use comm::select::{Select, Handle};
336 pub use comm::duplex::{DuplexStream, duplex};
339 { fn $name:ident() $b:block $(#[$a:meta])*} => (
341 #![allow(unused_imports)]
353 $(#[$a])* #[test] fn uv() { f() }
354 $(#[$a])* #[test] fn native() {
356 let (tx, rx) = channel();
357 native::task::spawn(proc() { tx.send(f()) });
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;
375 /// The receiving-half of Rust's channel type. This half can only be owned by
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,
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.
390 pub struct Messages<'a, T:'a> {
397 pub struct Messages<'a, T> {
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.
404 pub struct Sender<T> {
405 inner: UnsafeCell<Flavor<T>>,
407 // can't share in an arc
408 marker: marker::NoSync,
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,
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.
428 /// This channel's sending half has become disconnected, and there will
429 /// never be any more data received on this channel
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.
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.
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.
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>>>),
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()
463 unsafe fn inner<'a>(&'a self) -> &'a Flavor<T> {
464 &*self.inner_unsafe().get()
467 impl<T> UnsafeFlavor<T> for Sender<T> {
468 fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> {
472 impl<T> UnsafeFlavor<T> for Receiver<T> {
473 fn inner_unsafe<'a>(&'a self) -> &'a UnsafeCell<Flavor<T>> {
478 /// Creates a new asynchronous channel, returning the sender/receiver halves.
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").
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();
490 /// // Spawn off an expensive computation
492 /// # fn expensive_computation() {}
493 /// tx.send(expensive_computation());
496 /// // Do some useful work for awhile
498 /// // Let's see what that answer was
499 /// println!("{}", rx.recv());
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)))
507 /// Creates a new synchronous, bounded channel.
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.
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.
519 /// As with asynchronous channels, all senders will fail in `send` if the
520 /// `Receiver` has been destroyed.
525 /// let (tx, rx) = sync_channel(1);
527 /// // this returns immediately
531 /// // this will block until the previous message has been received
535 /// assert_eq!(rx.recv(), 1i);
536 /// assert_eq!(rx.recv(), 2i);
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)))
545 ////////////////////////////////////////////////////////////////////////////////
547 ////////////////////////////////////////////////////////////////////////////////
549 impl<T: Send> Sender<T> {
550 fn new(inner: Flavor<T>) -> Sender<T> {
552 inner: UnsafeCell::new(inner),
554 marker: marker::NoSync,
558 /// Sends a value along this channel to be received by the corresponding
561 /// Rust channels are infinitely buffered so this method will never block.
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.
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.
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");
585 /// Attempts to send a value on this channel, returning it back if it could
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`.
596 /// Like `send`, this method will never block.
600 /// This method will never fail, it will return the message back to the
601 /// caller if the other end is disconnected
606 /// let (tx, rx) = channel();
608 /// // This send is always successful
609 /// assert_eq!(tx.send_opt(1i), Ok(()));
611 /// // This send will fail because the receiver is gone
613 /// assert_eq!(tx.send_opt(1i), Err(1));
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.
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
625 let cnt = self.sends.get() + 1;
627 if cnt % (RESCHED_FREQ as uint) == 0 {
628 let task: Option<Box<Task>> = Local::try_take();
629 task.map(|t| t.maybe_yield());
632 let (new_inner, ret) = match *unsafe { self.inner() } {
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);
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
650 (*a.get()).send(t).ok().unwrap();
651 task.wake().map(|t| t.reawaken());
658 Stream(ref p) => return unsafe { (*p.get()).send(t) },
659 Shared(ref p) => return unsafe { (*p.get()).send(t) },
660 Sync(..) => unreachable!(),
664 let tmp = Sender::new(Stream(new_inner));
665 mem::swap(self.mut_inner(), tmp.mut_inner());
672 impl<T: Send> Clone for Sender<T> {
673 fn clone(&self) -> Sender<T> {
674 let (packet, sleeper) = match *unsafe { self.inner() } {
676 let a = Arc::new(UnsafeCell::new(shared::Packet::new()));
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))
686 let a = Arc::new(UnsafeCell::new(shared::Packet::new()));
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)),
696 unsafe { (*p.get()).clone_chan(); }
697 return Sender::new(Shared(p.clone()));
699 Sync(..) => unreachable!(),
703 (*packet.get()).inherit_blocker(sleeper);
705 let tmp = Sender::new(Shared(packet.clone()));
706 mem::swap(self.mut_inner(), tmp.mut_inner());
708 Sender::new(Shared(packet))
713 impl<T: Send> Drop for Sender<T> {
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!(),
724 ////////////////////////////////////////////////////////////////////////////////
726 ////////////////////////////////////////////////////////////////////////////////
728 impl<T: Send> SyncSender<T> {
729 fn new(inner: Arc<UnsafeCell<sync::Packet<T>>>) -> SyncSender<T> {
730 SyncSender { inner: inner, marker: marker::NoSync }
733 /// Sends a value on this synchronous channel.
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.
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.
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.
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
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");
761 /// Send a value on a channel, returning it back if the receiver
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.
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) }
777 /// Attempts to send a value on this channel without blocking.
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).
784 /// See `SyncSender::send` for notes about guarantees of whether the
785 /// receiver has received the data or not if this function is successful.
789 /// This function cannot fail
790 #[unstable = "the return type of this function is candidate for \
792 pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
793 unsafe { (*self.inner.get()).try_send(t) }
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());
806 impl<T: Send> Drop for SyncSender<T> {
808 unsafe { (*self.inner.get()).drop_chan(); }
812 ////////////////////////////////////////////////////////////////////////////////
814 ////////////////////////////////////////////////////////////////////////////////
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 }
821 /// Blocks waiting for a value on this receiver
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.
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.
833 /// If failure is not desired, then there are two options:
835 /// * If blocking is still desired, the `recv_opt` method will return `None`
836 /// when the other end hangs up
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() {
845 Err(()) => fail!("receiving on a closed channel"),
849 /// Attempts to return a pending value on this receiver without blocking
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.
855 /// This is useful for a flavor of "optimistic check" before deciding to
856 /// block on a receiver.
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());
873 let new_port = match *unsafe { self.inner() } {
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,
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,
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),
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),
906 mem::swap(self.mut_inner(),
907 new_port.mut_inner());
912 /// Attempt to wait for a value on this receiver, but does not fail if the
913 /// corresponding channel has hung up.
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.
919 /// In other words, this function has the same semantics as the `recv`
920 /// method except for the failure aspect.
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, ()> {
927 let new_port = match *unsafe { self.inner() } {
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,
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,
945 match unsafe { (*p.get()).recv() } {
946 Ok(t) => return Ok(t),
947 Err(shared::Empty) => return unreachable!(),
948 Err(shared::Disconnected) => return Err(()),
951 Sync(ref p) => return unsafe { (*p.get()).recv() }
954 mem::swap(self.mut_inner(), new_port.mut_inner());
959 /// Returns an iterator which will block waiting for messages, but never
960 /// `fail!`. It will return `None` when the channel has hung up.
962 pub fn iter<'a>(&'a self) -> Messages<'a, T> {
963 Messages { rx: self }
967 impl<T: Send> select::Packet for Receiver<T> {
968 fn can_recv(&self) -> bool {
970 let new_port = match *unsafe { self.inner() } {
972 match unsafe { (*p.get()).can_recv() } {
973 Ok(ret) => return ret,
974 Err(upgrade) => upgrade,
978 match unsafe { (*p.get()).can_recv() } {
979 Ok(ret) => return ret,
980 Err(upgrade) => upgrade,
984 return unsafe { (*p.get()).can_recv() };
987 return unsafe { (*p.get()).can_recv() };
991 mem::swap(self.mut_inner(),
992 new_port.mut_inner());
997 fn start_selection(&self, mut task: BlockedTask) -> Result<(), BlockedTask>{
999 let (t, new_port) = match *unsafe { self.inner() } {
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),
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),
1015 return unsafe { (*p.get()).start_selection(task) };
1018 return unsafe { (*p.get()).start_selection(task) };
1023 mem::swap(self.mut_inner(),
1024 new_port.mut_inner());
1029 fn abort_selection(&self) -> bool {
1030 let mut was_upgrade = false;
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)
1037 Shared(ref p) => return unsafe {
1038 (*p.get()).abort_selection(was_upgrade)
1040 Sync(ref p) => return unsafe {
1041 (*p.get()).abort_selection()
1044 let new_port = match result { Ok(b) => return b, Err(p) => p };
1047 mem::swap(self.mut_inner(),
1048 new_port.mut_inner());
1055 impl<'a, T: Send> Iterator<T> for Messages<'a, T> {
1056 fn next(&mut self) -> Option<T> { self.rx.recv_opt().ok() }
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(); },
1073 use std::prelude::*;
1079 pub fn stress_factor() -> uint {
1080 match os::getenv("RUST_TEST_STRESS") {
1081 Some(val) => from_str::<uint>(val.as_slice()).unwrap(),
1087 let (tx, rx) = channel::<int>();
1089 assert_eq!(rx.recv(), 1);
1092 test!(fn drop_full() {
1093 let (tx, _rx) = channel();
1097 test!(fn drop_full_shared() {
1098 let (tx, _rx) = channel();
1104 test!(fn smoke_shared() {
1105 let (tx, rx) = channel::<int>();
1107 assert_eq!(rx.recv(), 1);
1108 let tx = tx.clone();
1110 assert_eq!(rx.recv(), 1);
1113 test!(fn smoke_threads() {
1114 let (tx, rx) = channel::<int>();
1118 assert_eq!(rx.recv(), 1);
1121 test!(fn smoke_port_gone() {
1122 let (tx, rx) = channel::<int>();
1127 test!(fn smoke_shared_port_gone() {
1128 let (tx, rx) = channel::<int>();
1133 test!(fn smoke_shared_port_gone2() {
1134 let (tx, rx) = channel::<int>();
1136 let tx2 = tx.clone();
1141 test!(fn port_gone_concurrent() {
1142 let (tx, rx) = channel::<int>();
1149 test!(fn port_gone_concurrent_shared() {
1150 let (tx, rx) = channel::<int>();
1151 let tx2 = tx.clone();
1161 test!(fn smoke_chan_gone() {
1162 let (tx, rx) = channel::<int>();
1167 test!(fn smoke_chan_gone_shared() {
1168 let (tx, rx) = channel::<()>();
1169 let tx2 = tx.clone();
1175 test!(fn chan_gone_concurrent() {
1176 let (tx, rx) = channel::<int>();
1185 let (tx, rx) = channel::<int>();
1187 for _ in range(0u, 10000) { tx.send(1i); }
1189 for _ in range(0u, 10000) {
1190 assert_eq!(rx.recv(), 1);
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::<()>();
1201 for _ in range(0, AMT * NTHREADS) {
1202 assert_eq!(rx.recv(), 1);
1204 match rx.try_recv() {
1211 for _ in range(0, NTHREADS) {
1212 let tx = tx.clone();
1214 for _ in range(0, AMT) { tx.send(1); }
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();
1229 for _ in range(0i, 40) {
1230 assert_eq!(rx2.recv(), 1);
1235 native::task::spawn(proc() {
1236 for _ in range(0i, 40) {
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);
1255 for _ in range(0u, 40) {
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);
1272 native::task::spawn(proc() {
1274 assert_eq!(rx2.recv(), 2);
1281 test!(fn oneshot_single_thread_close_port_first() {
1282 // Simple test of closing without sending
1283 let (_tx, rx) = channel::<int>();
1287 test!(fn oneshot_single_thread_close_chan_first() {
1288 // Simple test of closing without sending
1289 let (tx, _rx) = channel::<int>();
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>>();
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>();
1308 assert!(res.is_err());
1311 test!(fn oneshot_single_thread_send_then_recv() {
1312 let (tx, rx) = channel::<Box<int>>();
1314 assert!(rx.recv() == box 10);
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);
1323 test!(fn oneshot_single_thread_try_send_closed() {
1324 let (tx, rx) = channel::<int>();
1326 assert!(tx.send_opt(10).is_err());
1329 test!(fn oneshot_single_thread_try_recv_open() {
1330 let (tx, rx) = channel::<int>();
1332 assert!(rx.recv_opt() == Ok(10));
1335 test!(fn oneshot_single_thread_try_recv_closed() {
1336 let (tx, rx) = channel::<int>();
1338 assert!(rx.recv_opt() == Err(()));
1341 test!(fn oneshot_single_thread_peek_data() {
1342 let (tx, rx) = channel::<int>();
1343 assert_eq!(rx.try_recv(), Err(Empty))
1345 assert_eq!(rx.try_recv(), Ok(10));
1348 test!(fn oneshot_single_thread_peek_close() {
1349 let (tx, rx) = channel::<int>();
1351 assert_eq!(rx.try_recv(), Err(Disconnected));
1352 assert_eq!(rx.try_recv(), Err(Disconnected));
1355 test!(fn oneshot_single_thread_peek_open() {
1356 let (_tx, rx) = channel::<int>();
1357 assert_eq!(rx.try_recv(), Err(Empty));
1360 test!(fn oneshot_multi_task_recv_then_send() {
1361 let (tx, rx) = channel::<Box<int>>();
1363 assert!(rx.recv() == box 10);
1369 test!(fn oneshot_multi_task_recv_then_close() {
1370 let (tx, rx) = channel::<Box<int>>();
1374 let res = task::try(proc() {
1375 assert!(rx.recv() == box 10);
1377 assert!(res.is_err());
1380 test!(fn oneshot_multi_thread_close_stress() {
1381 for _ in range(0, stress_factor()) {
1382 let (tx, rx) = channel::<int>();
1390 test!(fn oneshot_multi_thread_send_close_stress() {
1391 for _ in range(0, stress_factor()) {
1392 let (tx, rx) = channel::<int>();
1396 let _ = task::try(proc() {
1402 test!(fn oneshot_multi_thread_recv_close_stress() {
1403 for _ in range(0, stress_factor()) {
1404 let (tx, rx) = channel::<int>();
1406 let res = task::try(proc() {
1409 assert!(res.is_err());
1419 test!(fn oneshot_multi_thread_send_recv_stress() {
1420 for _ in range(0, stress_factor()) {
1421 let (tx, rx) = channel();
1426 assert!(rx.recv() == box 10i);
1431 test!(fn stream_send_recv_stress() {
1432 for _ in range(0, stress_factor()) {
1433 let (tx, rx) = channel();
1438 fn send(tx: Sender<Box<int>>, i: int) {
1439 if i == 10 { return }
1447 fn recv(rx: Receiver<Box<int>>, i: int) {
1448 if i == 10 { return }
1451 assert!(rx.recv() == box i);
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(); }
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();
1475 for _ in range(0, total) {
1480 test!(fn test_nested_recv_iter() {
1481 let (tx, rx) = channel::<int>();
1482 let (total_tx, total_rx) = channel::<int>();
1486 for x in rx.iter() {
1496 assert_eq!(total_rx.recv(), 6);
1499 test!(fn test_recv_iter_break() {
1500 let (tx, rx) = channel::<int>();
1501 let (count_tx, count_rx) = channel();
1505 for x in rx.iter() {
1512 count_tx.send(count);
1518 let _ = tx.send_opt(2);
1520 assert_eq!(count_rx.recv(), 4);
1523 test!(fn try_recv_states() {
1524 let (tx1, rx1) = channel::<int>();
1525 let (tx2, rx2) = channel::<()>();
1526 let (tx3, rx3) = channel::<()>();
1536 assert_eq!(rx1.try_recv(), Err(Empty));
1539 assert_eq!(rx1.try_recv(), Ok(1));
1540 assert_eq!(rx1.try_recv(), Err(Empty));
1543 assert_eq!(rx1.try_recv(), Err(Disconnected));
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();
1552 rx.recv(); // wait on a oneshot
1553 drop(rx); // destroy a shared
1556 // make sure the other task has gone to sleep
1557 for _ in range(0u, 5000) { task::deschedule(); }
1559 // upgrade to a shared chan and send a message
1564 // wait for the child task to exit before we exit
1568 test!(fn sends_off_the_runtime() {
1569 use std::rt::thread::Thread;
1571 let (tx, rx) = channel();
1572 let t = Thread::start(proc() {
1573 for _ in range(0u, 1000) {
1577 for _ in range(0u, 1000) {
1583 test!(fn try_recvs_off_the_runtime() {
1584 use std::rt::thread::Thread;
1586 let (tx, rx) = channel();
1587 let (cdone, pdone) = channel();
1588 let t = Thread::start(proc() {
1591 match rx.try_recv() {
1592 Ok(()) => { hits += 1; }
1593 Err(Empty) => { Thread::yield_now(); }
1594 Err(Disconnected) => return,
1599 for _ in range(0u, 10) {
1609 use std::prelude::*;
1612 pub fn stress_factor() -> uint {
1613 match os::getenv("RUST_TEST_STRESS") {
1614 Some(val) => from_str::<uint>(val.as_slice()).unwrap(),
1620 let (tx, rx) = sync_channel::<int>(1);
1622 assert_eq!(rx.recv(), 1);
1625 test!(fn drop_full() {
1626 let (tx, _rx) = sync_channel(1);
1630 test!(fn smoke_shared() {
1631 let (tx, rx) = sync_channel::<int>(1);
1633 assert_eq!(rx.recv(), 1);
1634 let tx = tx.clone();
1636 assert_eq!(rx.recv(), 1);
1639 test!(fn smoke_threads() {
1640 let (tx, rx) = sync_channel::<int>(0);
1644 assert_eq!(rx.recv(), 1);
1647 test!(fn smoke_port_gone() {
1648 let (tx, rx) = sync_channel::<int>(0);
1653 test!(fn smoke_shared_port_gone2() {
1654 let (tx, rx) = sync_channel::<int>(0);
1656 let tx2 = tx.clone();
1661 test!(fn port_gone_concurrent() {
1662 let (tx, rx) = sync_channel::<int>(0);
1669 test!(fn port_gone_concurrent_shared() {
1670 let (tx, rx) = sync_channel::<int>(0);
1671 let tx2 = tx.clone();
1681 test!(fn smoke_chan_gone() {
1682 let (tx, rx) = sync_channel::<int>(0);
1687 test!(fn smoke_chan_gone_shared() {
1688 let (tx, rx) = sync_channel::<()>(0);
1689 let tx2 = tx.clone();
1695 test!(fn chan_gone_concurrent() {
1696 let (tx, rx) = sync_channel::<int>(0);
1705 let (tx, rx) = sync_channel::<int>(0);
1707 for _ in range(0u, 10000) { tx.send(1); }
1709 for _ in range(0u, 10000) {
1710 assert_eq!(rx.recv(), 1);
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);
1721 for _ in range(0, AMT * NTHREADS) {
1722 assert_eq!(rx.recv(), 1);
1724 match rx.try_recv() {
1731 for _ in range(0, NTHREADS) {
1732 let tx = tx.clone();
1734 for _ in range(0, AMT) { tx.send(1); }
1741 test!(fn oneshot_single_thread_close_port_first() {
1742 // Simple test of closing without sending
1743 let (_tx, rx) = sync_channel::<int>(0);
1747 test!(fn oneshot_single_thread_close_chan_first() {
1748 // Simple test of closing without sending
1749 let (tx, _rx) = sync_channel::<int>(0);
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);
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);
1768 assert!(res.is_err());
1771 test!(fn oneshot_single_thread_send_then_recv() {
1772 let (tx, rx) = sync_channel::<Box<int>>(1);
1774 assert!(rx.recv() == box 10);
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);
1783 test!(fn oneshot_single_thread_try_send_closed() {
1784 let (tx, rx) = sync_channel::<int>(0);
1786 assert_eq!(tx.try_send(10), Err(RecvDisconnected(10)));
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)));
1794 test!(fn oneshot_single_thread_try_recv_open() {
1795 let (tx, rx) = sync_channel::<int>(1);
1797 assert!(rx.recv_opt() == Ok(10));
1800 test!(fn oneshot_single_thread_try_recv_closed() {
1801 let (tx, rx) = sync_channel::<int>(0);
1803 assert!(rx.recv_opt() == Err(()));
1806 test!(fn oneshot_single_thread_peek_data() {
1807 let (tx, rx) = sync_channel::<int>(1);
1808 assert_eq!(rx.try_recv(), Err(Empty))
1810 assert_eq!(rx.try_recv(), Ok(10));
1813 test!(fn oneshot_single_thread_peek_close() {
1814 let (tx, rx) = sync_channel::<int>(0);
1816 assert_eq!(rx.try_recv(), Err(Disconnected));
1817 assert_eq!(rx.try_recv(), Err(Disconnected));
1820 test!(fn oneshot_single_thread_peek_open() {
1821 let (_tx, rx) = sync_channel::<int>(0);
1822 assert_eq!(rx.try_recv(), Err(Empty));
1825 test!(fn oneshot_multi_task_recv_then_send() {
1826 let (tx, rx) = sync_channel::<Box<int>>(0);
1828 assert!(rx.recv() == box 10);
1834 test!(fn oneshot_multi_task_recv_then_close() {
1835 let (tx, rx) = sync_channel::<Box<int>>(0);
1839 let res = task::try(proc() {
1840 assert!(rx.recv() == box 10);
1842 assert!(res.is_err());
1845 test!(fn oneshot_multi_thread_close_stress() {
1846 for _ in range(0, stress_factor()) {
1847 let (tx, rx) = sync_channel::<int>(0);
1855 test!(fn oneshot_multi_thread_send_close_stress() {
1856 for _ in range(0, stress_factor()) {
1857 let (tx, rx) = sync_channel::<int>(0);
1861 let _ = task::try(proc() {
1867 test!(fn oneshot_multi_thread_recv_close_stress() {
1868 for _ in range(0, stress_factor()) {
1869 let (tx, rx) = sync_channel::<int>(0);
1871 let res = task::try(proc() {
1874 assert!(res.is_err());
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);
1891 assert!(rx.recv() == box 10i);
1896 test!(fn stream_send_recv_stress() {
1897 for _ in range(0, stress_factor()) {
1898 let (tx, rx) = sync_channel::<Box<int>>(0);
1903 fn send(tx: SyncSender<Box<int>>, i: int) {
1904 if i == 10 { return }
1912 fn recv(rx: Receiver<Box<int>>, i: int) {
1913 if i == 10 { return }
1916 assert!(rx.recv() == box i);
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(); }
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();
1940 for _ in range(0, total) {
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);
1951 for x in rx.iter() {
1961 assert_eq!(total_rx.recv(), 6);
1964 test!(fn test_recv_iter_break() {
1965 let (tx, rx) = sync_channel::<int>(0);
1966 let (count_tx, count_rx) = sync_channel(0);
1970 for x in rx.iter() {
1977 count_tx.send(count);
1983 let _ = tx.try_send(2);
1985 assert_eq!(count_rx.recv(), 4);
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);
2001 assert_eq!(rx1.try_recv(), Err(Empty));
2004 assert_eq!(rx1.try_recv(), Ok(1));
2005 assert_eq!(rx1.try_recv(), Err(Empty));
2008 assert_eq!(rx1.try_recv(), Err(Disconnected));
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);
2017 rx.recv(); // wait on a oneshot
2018 drop(rx); // destroy a shared
2021 // make sure the other task has gone to sleep
2022 for _ in range(0u, 5000) { task::deschedule(); }
2024 // upgrade to a shared chan and send a message
2029 // wait for the child task to exit before we exit
2033 test!(fn try_recvs_off_the_runtime() {
2034 use std::rt::thread::Thread;
2036 let (tx, rx) = sync_channel::<()>(0);
2037 let (cdone, pdone) = channel();
2038 let t = Thread::start(proc() {
2041 match rx.try_recv() {
2042 Ok(()) => { hits += 1; }
2043 Err(Empty) => { Thread::yield_now(); }
2044 Err(Disconnected) => return,
2049 for _ in range(0u, 10) {
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(()));
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));
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));
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();
2081 assert_eq!(tx.send_opt(1), Err(1));
2085 assert_eq!(tx2.send_opt(2), Err(2));
2093 test!(fn try_send1() {
2094 let (tx, _rx) = sync_channel::<int>(0);
2095 assert_eq!(tx.try_send(1), Err(Full(1)));
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)));
2104 test!(fn try_send3() {
2105 let (tx, rx) = sync_channel::<int>(1);
2106 assert_eq!(tx.try_send(1), Ok(()));
2108 assert_eq!(tx.try_send(1), Err(RecvDisconnected(1)));
2111 test!(fn try_send4() {
2112 let (tx, rx) = sync_channel::<int>(0);
2114 for _ in range(0u, 1000) { task::deschedule(); }
2115 assert_eq!(tx.try_send(1), Ok(()));
2117 assert_eq!(rx.recv(), 1);
2118 } #[ignore(reason = "flaky on libnative")])
2120 test!(fn issue_15761() {
2122 let (tx1, rx1) = sync_channel::<()>(3);
2123 let (tx2, rx2) = sync_channel::<()>(3);
2127 tx2.try_send(()).unwrap();
2130 tx1.try_send(()).unwrap();
2134 for _ in range(0u, 100) {