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 //! let (tx, rx) = channel();
90 //! for i in range(0i, 10i) {
91 //! let tx = tx.clone();
97 //! for _ in range(0i, 10i) {
98 //! let j = rx.recv();
99 //! assert!(0 <= j && j < 10);
103 //! Propagating failure:
106 //! // The call to recv() will fail!() because the channel has already hung
107 //! // up (or been deallocated)
108 //! let (tx, rx) = channel::<int>();
113 //! Synchronous channels:
116 //! let (tx, rx) = sync_channel::<int>(0);
118 //! // This will wait for the parent task to start receiving
124 //! Reading from a channel with a timeout requires to use a Timer together
125 //! with the channel. You can use the select! macro to select either and
126 //! handle the timeout case. This first example will break out of the loop
127 //! after 10 seconds no matter what:
130 //! use std::io::timer::Timer;
132 //! let (tx, rx) = channel::<int>();
133 //! let mut timer = Timer::new().unwrap();
134 //! let timeout = timer.oneshot(10000);
138 //! val = rx.recv() => println!("Received {}", val),
139 //! () = timeout.recv() => {
140 //! println!("timed out, total time was more than 10 seconds")
147 //! This second example is more costly since it allocates a new timer every
148 //! time a message is received, but it allows you to timeout after the channel
149 //! has been inactive for 5 seconds:
152 //! use std::io::timer::Timer;
154 //! let (tx, rx) = channel::<int>();
155 //! let mut timer = Timer::new().unwrap();
158 //! let timeout = timer.oneshot(5000);
161 //! val = rx.recv() => println!("Received {}", val),
162 //! () = timeout.recv() => {
163 //! println!("timed out, no message received in 5 seconds")
170 // A description of how Rust's channel implementation works
172 // Channels are supposed to be the basic building block for all other
173 // concurrent primitives that are used in Rust. As a result, the channel type
174 // needs to be highly optimized, flexible, and broad enough for use everywhere.
176 // The choice of implementation of all channels is to be built on lock-free data
177 // structures. The channels themselves are then consequently also lock-free data
178 // structures. As always with lock-free code, this is a very "here be dragons"
179 // territory, especially because I'm unaware of any academic papers which have
180 // gone into great length about channels of these flavors.
182 // ## Flavors of channels
184 // From the perspective of a consumer of this library, there is only one flavor
185 // of channel. This channel can be used as a stream and cloned to allow multiple
186 // senders. Under the hood, however, there are actually three flavors of
189 // * Oneshots - these channels are highly optimized for the one-send use case.
190 // They contain as few atomics as possible and involve one and
191 // exactly one allocation.
192 // * Streams - these channels are optimized for the non-shared use case. They
193 // use a different concurrent queue which is more tailored for this
194 // use case. The initial allocation of this flavor of channel is not
196 // * Shared - this is the most general form of channel that this module offers,
197 // a channel with multiple senders. This type is as optimized as it
198 // can be, but the previous two types mentioned are much faster for
201 // ## Concurrent queues
203 // The basic idea of Rust's Sender/Receiver types is that send() never blocks, but
204 // recv() obviously blocks. This means that under the hood there must be some
205 // shared and concurrent queue holding all of the actual data.
207 // With two flavors of channels, two flavors of queues are also used. We have
208 // chosen to use queues from a well-known author which are abbreviated as SPSC
209 // and MPSC (single producer, single consumer and multiple producer, single
210 // consumer). SPSC queues are used for streams while MPSC queues are used for
213 // ### SPSC optimizations
215 // The SPSC queue found online is essentially a linked list of nodes where one
216 // half of the nodes are the "queue of data" and the other half of nodes are a
217 // cache of unused nodes. The unused nodes are used such that an allocation is
218 // not required on every push() and a free doesn't need to happen on every
221 // As found online, however, the cache of nodes is of an infinite size. This
222 // means that if a channel at one point in its life had 50k items in the queue,
223 // then the queue will always have the capacity for 50k items. I believed that
224 // this was an unnecessary limitation of the implementation, so I have altered
225 // the queue to optionally have a bound on the cache size.
227 // By default, streams will have an unbounded SPSC queue with a small-ish cache
228 // size. The hope is that the cache is still large enough to have very fast
229 // send() operations while not too large such that millions of channels can
232 // ### MPSC optimizations
234 // Right now the MPSC queue has not been optimized. Like the SPSC queue, it uses
235 // a linked list under the hood to earn its unboundedness, but I have not put
236 // forth much effort into having a cache of nodes similar to the SPSC queue.
238 // For now, I believe that this is "ok" because shared channels are not the most
239 // common type, but soon we may wish to revisit this queue choice and determine
240 // another candidate for backend storage of shared channels.
242 // ## Overview of the Implementation
244 // Now that there's a little background on the concurrent queues used, it's
245 // worth going into much more detail about the channels themselves. The basic
246 // pseudocode for a send/recv are:
250 // queue.push(t) return if queue.pop()
251 // if increment() == -1 deschedule {
252 // wakeup() if decrement() > 0
253 // cancel_deschedule()
257 // As mentioned before, there are no locks in this implementation, only atomic
258 // instructions are used.
260 // ### The internal atomic counter
262 // Every channel has a shared counter with each half to keep track of the size
263 // of the queue. This counter is used to abort descheduling by the receiver and
264 // to know when to wake up on the sending side.
266 // As seen in the pseudocode, senders will increment this count and receivers
267 // will decrement the count. The theory behind this is that if a sender sees a
268 // -1 count, it will wake up the receiver, and if the receiver sees a 1+ count,
269 // then it doesn't need to block.
271 // The recv() method has a beginning call to pop(), and if successful, it needs
272 // to decrement the count. It is a crucial implementation detail that this
273 // decrement does *not* happen to the shared counter. If this were the case,
274 // then it would be possible for the counter to be very negative when there were
275 // no receivers waiting, in which case the senders would have to determine when
276 // it was actually appropriate to wake up a receiver.
278 // Instead, the "steal count" is kept track of separately (not atomically
279 // because it's only used by receivers), and then the decrement() call when
280 // descheduling will lump in all of the recent steals into one large decrement.
282 // The implication of this is that if a sender sees a -1 count, then there's
283 // guaranteed to be a waiter waiting!
285 // ## Native Implementation
287 // A major goal of these channels is to work seamlessly on and off the runtime.
288 // All of the previous race conditions have been worded in terms of
289 // scheduler-isms (which is obviously not available without the runtime).
291 // For now, native usage of channels (off the runtime) will fall back onto
292 // mutexes/cond vars for descheduling/atomic decisions. The no-contention path
293 // is still entirely lock-free, the "deschedule" blocks above are surrounded by
294 // a mutex and the "wakeup" blocks involve grabbing a mutex and signaling on a
295 // condition variable.
299 // Being able to support selection over channels has greatly influenced this
300 // design, and not only does selection need to work inside the runtime, but also
301 // outside the runtime.
303 // The implementation is fairly straightforward. The goal of select() is not to
304 // return some data, but only to return which channel can receive data without
305 // blocking. The implementation is essentially the entire blocking procedure
306 // followed by an increment as soon as its woken up. The cancellation procedure
307 // involves an increment and swapping out of to_wake to acquire ownership of the
310 // Sadly this current implementation requires multiple allocations, so I have
311 // seen the throughput of select() be much worse than it should be. I do not
312 // believe that there is anything fundamental which needs to change about these
313 // channels, however, in order to support a more efficient select().
317 // And now that you've seen all the races that I found and attempted to fix,
318 // here's the code for you to find some more!
320 use core::prelude::*;
323 use alloc::owned::Box;
324 use core::cell::Cell;
325 use core::kinds::marker;
327 use core::ty::Unsafe;
328 use rustrt::local::Local;
329 use rustrt::task::{Task, BlockedTask};
331 pub use comm::select::{Select, Handle};
332 pub use comm::duplex::{DuplexStream, duplex};
335 { fn $name:ident() $b:block $(#[$a:meta])*} => (
337 #![allow(unused_imports)]
349 $(#[$a])* #[test] fn uv() { f() }
350 $(#[$a])* #[test] fn native() {
352 let (tx, rx) = channel();
353 native::task::spawn(proc() { tx.send(f()) });
367 // Use a power of 2 to allow LLVM to optimize to something that's not a
368 // division, this is hit pretty regularly.
369 static RESCHED_FREQ: int = 256;
371 /// The receiving-half of Rust's channel type. This half can only be owned by
374 pub struct Receiver<T> {
375 inner: Unsafe<Flavor<T>>,
376 receives: Cell<uint>,
377 // can't share in an arc
378 marker: marker::NoShare,
381 /// An iterator over messages on a receiver, this iterator will block
382 /// whenever `next` is called, waiting for a new message, and `None` will be
383 /// returned when the corresponding channel has hung up.
385 pub struct Messages<'a, T> {
389 /// The sending-half of Rust's asynchronous channel type. This half can only be
390 /// owned by one task, but it can be cloned to send to other tasks.
392 pub struct Sender<T> {
393 inner: Unsafe<Flavor<T>>,
395 // can't share in an arc
396 marker: marker::NoShare,
399 /// The sending-half of Rust's synchronous channel type. This half can only be
400 /// owned by one task, but it can be cloned to send to other tasks.
401 #[unstable = "this type may be renamed, but it will always exist"]
402 pub struct SyncSender<T> {
403 inner: Arc<Unsafe<sync::Packet<T>>>,
404 // can't share in an arc
405 marker: marker::NoShare,
408 /// This enumeration is the list of the possible reasons that try_recv could not
409 /// return data when called.
410 #[deriving(PartialEq, Clone, Show)]
411 #[experimental = "this is likely to be removed in changing try_recv()"]
412 pub enum TryRecvError {
413 /// This channel is currently empty, but the sender(s) have not yet
414 /// disconnected, so data may yet become available.
416 /// This channel's sending half has become disconnected, and there will
417 /// never be any more data received on this channel
421 /// This enumeration is the list of the possible error outcomes for the
422 /// `SyncSender::try_send` method.
423 #[deriving(PartialEq, Clone, Show)]
424 #[experimental = "this is likely to be removed in changing try_send()"]
425 pub enum TrySendError<T> {
426 /// The data could not be sent on the channel because it would require that
427 /// the callee block to send the data.
429 /// If this is a buffered channel, then the buffer is full at this time. If
430 /// this is not a buffered channel, then there is no receiver available to
431 /// acquire the data.
433 /// This channel's receiving half has disconnected, so the data could not be
434 /// sent. The data is returned back to the callee in this case.
439 Oneshot(Arc<Unsafe<oneshot::Packet<T>>>),
440 Stream(Arc<Unsafe<stream::Packet<T>>>),
441 Shared(Arc<Unsafe<shared::Packet<T>>>),
442 Sync(Arc<Unsafe<sync::Packet<T>>>),
446 trait UnsafeFlavor<T> {
447 fn inner_unsafe<'a>(&'a self) -> &'a Unsafe<Flavor<T>>;
448 unsafe fn mut_inner<'a>(&'a self) -> &'a mut Flavor<T> {
449 &mut *self.inner_unsafe().get()
451 unsafe fn inner<'a>(&'a self) -> &'a Flavor<T> {
452 &*self.inner_unsafe().get()
455 impl<T> UnsafeFlavor<T> for Sender<T> {
456 fn inner_unsafe<'a>(&'a self) -> &'a Unsafe<Flavor<T>> {
460 impl<T> UnsafeFlavor<T> for Receiver<T> {
461 fn inner_unsafe<'a>(&'a self) -> &'a Unsafe<Flavor<T>> {
466 /// Creates a new asynchronous channel, returning the sender/receiver halves.
468 /// All data sent on the sender will become available on the receiver, and no
469 /// send will block the calling task (this channel has an "infinite buffer").
474 /// let (tx, rx) = channel();
476 /// // Spawn off an expensive computation
478 /// # fn expensive_computation() {}
479 /// tx.send(expensive_computation());
482 /// // Do some useful work for awhile
484 /// // Let's see what that answer was
485 /// println!("{}", rx.recv());
488 pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) {
489 let a = Arc::new(Unsafe::new(oneshot::Packet::new()));
490 (Sender::new(Oneshot(a.clone())), Receiver::new(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 fail in `send` if the
506 /// `Receiver` has been destroyed.
511 /// let (tx, rx) = sync_channel(1);
513 /// // this returns immediately
517 /// // this will block until the previous message has been received
521 /// assert_eq!(rx.recv(), 1i);
522 /// assert_eq!(rx.recv(), 2i);
524 #[unstable = "this function may be renamed to more accurately reflect the type \
525 of channel that is is creating"]
526 pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) {
527 let a = Arc::new(Unsafe::new(sync::Packet::new(bound)));
528 (SyncSender::new(a.clone()), Receiver::new(Sync(a)))
531 ////////////////////////////////////////////////////////////////////////////////
533 ////////////////////////////////////////////////////////////////////////////////
535 impl<T: Send> Sender<T> {
536 fn new(inner: Flavor<T>) -> Sender<T> {
537 Sender { inner: Unsafe::new(inner), sends: Cell::new(0), marker: marker::NoShare }
540 /// Sends a value along this channel to be received by the corresponding
543 /// Rust channels are infinitely buffered so this method will never block.
547 /// This function will fail if the other end of the channel has hung up.
548 /// This means that if the corresponding receiver has fallen out of scope,
549 /// this function will trigger a fail message saying that a message is
550 /// being sent on a closed channel.
552 /// Note that if this function does *not* fail, it does not mean that the
553 /// data will be successfully received. All sends are placed into a queue,
554 /// so it is possible for a send to succeed (the other end is alive), but
555 /// then the other end could immediately disconnect.
557 /// The purpose of this functionality is to propagate failure among tasks.
558 /// If failure is not desired, then consider using the `send_opt` method
559 #[experimental = "this function is being considered candidate for removal \
560 to adhere to the general guidelines of rust"]
561 pub fn send(&self, t: T) {
562 if self.send_opt(t).is_err() {
563 fail!("sending on a closed channel");
567 /// Attempts to send a value on this channel, returning it back if it could
570 /// A successful send occurs when it is determined that the other end of
571 /// the channel has not hung up already. An unsuccessful send would be one
572 /// where the corresponding receiver has already been deallocated. Note
573 /// that a return value of `Err` means that the data will never be
574 /// received, but a return value of `Ok` does *not* mean that the data
575 /// will be received. It is possible for the corresponding receiver to
576 /// hang up immediately after this function returns `Ok`.
578 /// Like `send`, this method will never block.
582 /// This method will never fail, it will return the message back to the
583 /// caller if the other end is disconnected
588 /// let (tx, rx) = channel();
590 /// // This send is always successful
591 /// assert_eq!(tx.send_opt(1i), Ok(()));
593 /// // This send will fail because the receiver is gone
595 /// assert_eq!(tx.send_opt(1i), Err(1));
597 #[unstable = "this function may be renamed to send() in the future"]
598 pub fn send_opt(&self, t: T) -> Result<(), T> {
599 // In order to prevent starvation of other tasks in situations where
600 // a task sends repeatedly without ever receiving, we occasionally
601 // yield instead of doing a send immediately.
603 // Don't unconditionally attempt to yield because the TLS overhead can
604 // be a bit much, and also use `try_take` instead of `take` because
605 // there's no reason that this send shouldn't be usable off the
607 let cnt = self.sends.get() + 1;
609 if cnt % (RESCHED_FREQ as uint) == 0 {
610 let task: Option<Box<Task>> = Local::try_take();
611 task.map(|t| t.maybe_yield());
614 let (new_inner, ret) = match *unsafe { self.inner() } {
621 let a = Arc::new(Unsafe::new(stream::Packet::new()));
622 match (*p).upgrade(Receiver::new(Stream(a.clone()))) {
623 oneshot::UpSuccess => {
624 let ret = (*a.get()).send(t);
627 oneshot::UpDisconnected => (a, Err(t)),
628 oneshot::UpWoke(task) => {
629 // This send cannot fail because the task is
630 // asleep (we're looking at it), so the receiver
632 (*a.get()).send(t).ok().unwrap();
633 task.wake().map(|t| t.reawaken());
640 Stream(ref p) => return unsafe { (*p.get()).send(t) },
641 Shared(ref p) => return unsafe { (*p.get()).send(t) },
642 Sync(..) => unreachable!(),
646 let tmp = Sender::new(Stream(new_inner));
647 mem::swap(self.mut_inner(), tmp.mut_inner());
654 impl<T: Send> Clone for Sender<T> {
655 fn clone(&self) -> Sender<T> {
656 let (packet, sleeper) = match *unsafe { self.inner() } {
658 let a = Arc::new(Unsafe::new(shared::Packet::new()));
660 (*a.get()).postinit_lock();
661 match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
662 oneshot::UpSuccess | oneshot::UpDisconnected => (a, None),
663 oneshot::UpWoke(task) => (a, Some(task))
668 let a = Arc::new(Unsafe::new(shared::Packet::new()));
670 (*a.get()).postinit_lock();
671 match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) {
672 stream::UpSuccess | stream::UpDisconnected => (a, None),
673 stream::UpWoke(task) => (a, Some(task)),
678 unsafe { (*p.get()).clone_chan(); }
679 return Sender::new(Shared(p.clone()));
681 Sync(..) => unreachable!(),
685 (*packet.get()).inherit_blocker(sleeper);
687 let tmp = Sender::new(Shared(packet.clone()));
688 mem::swap(self.mut_inner(), tmp.mut_inner());
690 Sender::new(Shared(packet))
695 impl<T: Send> Drop for Sender<T> {
697 match *unsafe { self.mut_inner() } {
698 Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); },
699 Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); },
700 Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); },
701 Sync(..) => unreachable!(),
706 ////////////////////////////////////////////////////////////////////////////////
708 ////////////////////////////////////////////////////////////////////////////////
710 impl<T: Send> SyncSender<T> {
711 fn new(inner: Arc<Unsafe<sync::Packet<T>>>) -> SyncSender<T> {
712 SyncSender { inner: inner, marker: marker::NoShare }
715 /// Sends a value on this synchronous channel.
717 /// This function will *block* until space in the internal buffer becomes
718 /// available or a receiver is available to hand off the message to.
720 /// Note that a successful send does *not* guarantee that the receiver will
721 /// ever see the data if there is a buffer on this channel. Messages may be
722 /// enqueued in the internal buffer for the receiver to receive at a later
723 /// time. If the buffer size is 0, however, it can be guaranteed that the
724 /// receiver has indeed received the data if this function returns success.
728 /// Similarly to `Sender::send`, this function will fail if the
729 /// corresponding `Receiver` for this channel has disconnected. This
730 /// behavior is used to propagate failure among tasks.
732 /// If failure is not desired, you can achieve the same semantics with the
733 /// `SyncSender::send_opt` method which will not fail if the receiver
735 #[experimental = "this function is being considered candidate for removal \
736 to adhere to the general guidelines of rust"]
737 pub fn send(&self, t: T) {
738 if self.send_opt(t).is_err() {
739 fail!("sending on a closed channel");
743 /// Send a value on a channel, returning it back if the receiver
746 /// This method will *block* to send the value `t` on the channel, but if
747 /// the value could not be sent due to the receiver disconnecting, the value
748 /// is returned back to the callee. This function is similar to `try_send`,
749 /// except that it will block if the channel is currently full.
753 /// This function cannot fail.
754 #[unstable = "this function may be renamed to send() in the future"]
755 pub fn send_opt(&self, t: T) -> Result<(), T> {
756 unsafe { (*self.inner.get()).send(t) }
759 /// Attempts to send a value on this channel without blocking.
761 /// This method differs from `send_opt` by returning immediately if the
762 /// channel's buffer is full or no receiver is waiting to acquire some
763 /// data. Compared with `send_opt`, this function has two failure cases
764 /// instead of one (one for disconnection, one for a full buffer).
766 /// See `SyncSender::send` for notes about guarantees of whether the
767 /// receiver has received the data or not if this function is successful.
771 /// This function cannot fail
772 #[unstable = "the return type of this function is candidate for \
774 pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
775 unsafe { (*self.inner.get()).try_send(t) }
780 impl<T: Send> Clone for SyncSender<T> {
781 fn clone(&self) -> SyncSender<T> {
782 unsafe { (*self.inner.get()).clone_chan(); }
783 return SyncSender::new(self.inner.clone());
788 impl<T: Send> Drop for SyncSender<T> {
790 unsafe { (*self.inner.get()).drop_chan(); }
794 ////////////////////////////////////////////////////////////////////////////////
796 ////////////////////////////////////////////////////////////////////////////////
798 impl<T: Send> Receiver<T> {
799 fn new(inner: Flavor<T>) -> Receiver<T> {
800 Receiver { inner: Unsafe::new(inner), receives: Cell::new(0), marker: marker::NoShare }
803 /// Blocks waiting for a value on this receiver
805 /// This function will block if necessary to wait for a corresponding send
806 /// on the channel from its paired `Sender` structure. This receiver will
807 /// be woken up when data is ready, and the data will be returned.
811 /// Similar to channels, this method will trigger a task failure if the
812 /// other end of the channel has hung up (been deallocated). The purpose of
813 /// this is to propagate failure among tasks.
815 /// If failure is not desired, then there are two options:
817 /// * If blocking is still desired, the `recv_opt` method will return `None`
818 /// when the other end hangs up
820 /// * If blocking is not desired, then the `try_recv` method will attempt to
821 /// peek at a value on this receiver.
822 #[experimental = "this function is being considered candidate for removal \
823 to adhere to the general guidelines of rust"]
824 pub fn recv(&self) -> T {
825 match self.recv_opt() {
827 Err(()) => fail!("receiving on a closed channel"),
831 /// Attempts to return a pending value on this receiver without blocking
833 /// This method will never block the caller in order to wait for data to
834 /// become available. Instead, this will always return immediately with a
835 /// possible option of pending data on the channel.
837 /// This is useful for a flavor of "optimistic check" before deciding to
838 /// block on a receiver.
840 /// This function cannot fail.
841 #[unstable = "the return type of this function may be altered"]
842 pub fn try_recv(&self) -> Result<T, TryRecvError> {
843 // If a thread is spinning in try_recv, we should take the opportunity
844 // to reschedule things occasionally. See notes above in scheduling on
845 // sends for why this doesn't always hit TLS, and also for why this uses
846 // `try_take` instead of `take`.
847 let cnt = self.receives.get() + 1;
848 self.receives.set(cnt);
849 if cnt % (RESCHED_FREQ as uint) == 0 {
850 let task: Option<Box<Task>> = Local::try_take();
851 task.map(|t| t.maybe_yield());
855 let new_port = match *unsafe { self.inner() } {
857 match unsafe { (*p.get()).try_recv() } {
858 Ok(t) => return Ok(t),
859 Err(oneshot::Empty) => return Err(Empty),
860 Err(oneshot::Disconnected) => return Err(Disconnected),
861 Err(oneshot::Upgraded(rx)) => rx,
865 match unsafe { (*p.get()).try_recv() } {
866 Ok(t) => return Ok(t),
867 Err(stream::Empty) => return Err(Empty),
868 Err(stream::Disconnected) => return Err(Disconnected),
869 Err(stream::Upgraded(rx)) => rx,
873 match unsafe { (*p.get()).try_recv() } {
874 Ok(t) => return Ok(t),
875 Err(shared::Empty) => return Err(Empty),
876 Err(shared::Disconnected) => return Err(Disconnected),
880 match unsafe { (*p.get()).try_recv() } {
881 Ok(t) => return Ok(t),
882 Err(sync::Empty) => return Err(Empty),
883 Err(sync::Disconnected) => return Err(Disconnected),
888 mem::swap(self.mut_inner(),
889 new_port.mut_inner());
894 /// Attempt to wait for a value on this receiver, but does not fail if the
895 /// corresponding channel has hung up.
897 /// This implementation of iterators for ports will always block if there is
898 /// not data available on the receiver, but it will not fail in the case
899 /// that the channel has been deallocated.
901 /// In other words, this function has the same semantics as the `recv`
902 /// method except for the failure aspect.
904 /// If the channel has hung up, then `Err` is returned. Otherwise `Ok` of
905 /// the value found on the receiver is returned.
906 #[unstable = "this function may be renamed to recv()"]
907 pub fn recv_opt(&self) -> Result<T, ()> {
909 let new_port = match *unsafe { self.inner() } {
911 match unsafe { (*p.get()).recv() } {
912 Ok(t) => return Ok(t),
913 Err(oneshot::Empty) => return unreachable!(),
914 Err(oneshot::Disconnected) => return Err(()),
915 Err(oneshot::Upgraded(rx)) => rx,
919 match unsafe { (*p.get()).recv() } {
920 Ok(t) => return Ok(t),
921 Err(stream::Empty) => return unreachable!(),
922 Err(stream::Disconnected) => return Err(()),
923 Err(stream::Upgraded(rx)) => rx,
927 match unsafe { (*p.get()).recv() } {
928 Ok(t) => return Ok(t),
929 Err(shared::Empty) => return unreachable!(),
930 Err(shared::Disconnected) => return Err(()),
933 Sync(ref p) => return unsafe { (*p.get()).recv() }
936 mem::swap(self.mut_inner(), new_port.mut_inner());
941 /// Returns an iterator which will block waiting for messages, but never
942 /// `fail!`. It will return `None` when the channel has hung up.
944 pub fn iter<'a>(&'a self) -> Messages<'a, T> {
945 Messages { rx: self }
949 impl<T: Send> select::Packet for Receiver<T> {
950 fn can_recv(&self) -> bool {
952 let new_port = match *unsafe { self.inner() } {
954 match unsafe { (*p.get()).can_recv() } {
955 Ok(ret) => return ret,
956 Err(upgrade) => upgrade,
960 match unsafe { (*p.get()).can_recv() } {
961 Ok(ret) => return ret,
962 Err(upgrade) => upgrade,
966 return unsafe { (*p.get()).can_recv() };
969 return unsafe { (*p.get()).can_recv() };
973 mem::swap(self.mut_inner(),
974 new_port.mut_inner());
979 fn start_selection(&self, mut task: BlockedTask) -> Result<(), BlockedTask>{
981 let (t, new_port) = match *unsafe { self.inner() } {
983 match unsafe { (*p.get()).start_selection(task) } {
984 oneshot::SelSuccess => return Ok(()),
985 oneshot::SelCanceled(task) => return Err(task),
986 oneshot::SelUpgraded(t, rx) => (t, rx),
990 match unsafe { (*p.get()).start_selection(task) } {
991 stream::SelSuccess => return Ok(()),
992 stream::SelCanceled(task) => return Err(task),
993 stream::SelUpgraded(t, rx) => (t, rx),
997 return unsafe { (*p.get()).start_selection(task) };
1000 return unsafe { (*p.get()).start_selection(task) };
1005 mem::swap(self.mut_inner(),
1006 new_port.mut_inner());
1011 fn abort_selection(&self) -> bool {
1012 let mut was_upgrade = false;
1014 let result = match *unsafe { self.inner() } {
1015 Oneshot(ref p) => unsafe { (*p.get()).abort_selection() },
1016 Stream(ref p) => unsafe {
1017 (*p.get()).abort_selection(was_upgrade)
1019 Shared(ref p) => return unsafe {
1020 (*p.get()).abort_selection(was_upgrade)
1022 Sync(ref p) => return unsafe {
1023 (*p.get()).abort_selection()
1026 let new_port = match result { Ok(b) => return b, Err(p) => p };
1029 mem::swap(self.mut_inner(),
1030 new_port.mut_inner());
1037 impl<'a, T: Send> Iterator<T> for Messages<'a, T> {
1038 fn next(&mut self) -> Option<T> { self.rx.recv_opt().ok() }
1041 #[unsafe_destructor]
1042 impl<T: Send> Drop for Receiver<T> {
1043 fn drop(&mut self) {
1044 match *unsafe { self.mut_inner() } {
1045 Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); },
1046 Stream(ref mut p) => unsafe { (*p.get()).drop_port(); },
1047 Shared(ref mut p) => unsafe { (*p.get()).drop_port(); },
1048 Sync(ref mut p) => unsafe { (*p.get()).drop_port(); },
1055 use std::prelude::*;
1061 pub fn stress_factor() -> uint {
1062 match os::getenv("RUST_TEST_STRESS") {
1063 Some(val) => from_str::<uint>(val.as_slice()).unwrap(),
1069 let (tx, rx) = channel::<int>();
1071 assert_eq!(rx.recv(), 1);
1074 test!(fn drop_full() {
1075 let (tx, _rx) = channel();
1079 test!(fn drop_full_shared() {
1080 let (tx, _rx) = channel();
1086 test!(fn smoke_shared() {
1087 let (tx, rx) = channel::<int>();
1089 assert_eq!(rx.recv(), 1);
1090 let tx = tx.clone();
1092 assert_eq!(rx.recv(), 1);
1095 test!(fn smoke_threads() {
1096 let (tx, rx) = channel::<int>();
1100 assert_eq!(rx.recv(), 1);
1103 test!(fn smoke_port_gone() {
1104 let (tx, rx) = channel::<int>();
1109 test!(fn smoke_shared_port_gone() {
1110 let (tx, rx) = channel::<int>();
1115 test!(fn smoke_shared_port_gone2() {
1116 let (tx, rx) = channel::<int>();
1118 let tx2 = tx.clone();
1123 test!(fn port_gone_concurrent() {
1124 let (tx, rx) = channel::<int>();
1131 test!(fn port_gone_concurrent_shared() {
1132 let (tx, rx) = channel::<int>();
1133 let tx2 = tx.clone();
1143 test!(fn smoke_chan_gone() {
1144 let (tx, rx) = channel::<int>();
1149 test!(fn smoke_chan_gone_shared() {
1150 let (tx, rx) = channel::<()>();
1151 let tx2 = tx.clone();
1157 test!(fn chan_gone_concurrent() {
1158 let (tx, rx) = channel::<int>();
1167 let (tx, rx) = channel::<int>();
1169 for _ in range(0u, 10000) { tx.send(1i); }
1171 for _ in range(0u, 10000) {
1172 assert_eq!(rx.recv(), 1);
1176 test!(fn stress_shared() {
1177 static AMT: uint = 10000;
1178 static NTHREADS: uint = 8;
1179 let (tx, rx) = channel::<int>();
1180 let (dtx, drx) = channel::<()>();
1183 for _ in range(0, AMT * NTHREADS) {
1184 assert_eq!(rx.recv(), 1);
1186 match rx.try_recv() {
1193 for _ in range(0, NTHREADS) {
1194 let tx = tx.clone();
1196 for _ in range(0, AMT) { tx.send(1); }
1204 fn send_from_outside_runtime() {
1205 let (tx1, rx1) = channel::<()>();
1206 let (tx2, rx2) = channel::<int>();
1207 let (tx3, rx3) = channel::<()>();
1208 let tx4 = tx3.clone();
1211 for _ in range(0i, 40) {
1212 assert_eq!(rx2.recv(), 1);
1217 native::task::spawn(proc() {
1218 for _ in range(0i, 40) {
1228 fn recv_from_outside_runtime() {
1229 let (tx, rx) = channel::<int>();
1230 let (dtx, drx) = channel();
1231 native::task::spawn(proc() {
1232 for _ in range(0i, 40) {
1233 assert_eq!(rx.recv(), 1);
1237 for _ in range(0u, 40) {
1245 let (tx1, rx1) = channel::<int>();
1246 let (tx2, rx2) = channel::<int>();
1247 let (tx3, rx3) = channel::<()>();
1248 let tx4 = tx3.clone();
1249 native::task::spawn(proc() {
1250 assert_eq!(rx1.recv(), 1);
1254 native::task::spawn(proc() {
1256 assert_eq!(rx2.recv(), 2);
1263 test!(fn oneshot_single_thread_close_port_first() {
1264 // Simple test of closing without sending
1265 let (_tx, rx) = channel::<int>();
1269 test!(fn oneshot_single_thread_close_chan_first() {
1270 // Simple test of closing without sending
1271 let (tx, _rx) = channel::<int>();
1275 test!(fn oneshot_single_thread_send_port_close() {
1276 // Testing that the sender cleans up the payload if receiver is closed
1277 let (tx, rx) = channel::<Box<int>>();
1282 test!(fn oneshot_single_thread_recv_chan_close() {
1283 // Receiving on a closed chan will fail
1284 let res = task::try(proc() {
1285 let (tx, rx) = channel::<int>();
1290 assert!(res.is_err());
1293 test!(fn oneshot_single_thread_send_then_recv() {
1294 let (tx, rx) = channel::<Box<int>>();
1296 assert!(rx.recv() == box 10);
1299 test!(fn oneshot_single_thread_try_send_open() {
1300 let (tx, rx) = channel::<int>();
1301 assert!(tx.send_opt(10).is_ok());
1302 assert!(rx.recv() == 10);
1305 test!(fn oneshot_single_thread_try_send_closed() {
1306 let (tx, rx) = channel::<int>();
1308 assert!(tx.send_opt(10).is_err());
1311 test!(fn oneshot_single_thread_try_recv_open() {
1312 let (tx, rx) = channel::<int>();
1314 assert!(rx.recv_opt() == Ok(10));
1317 test!(fn oneshot_single_thread_try_recv_closed() {
1318 let (tx, rx) = channel::<int>();
1320 assert!(rx.recv_opt() == Err(()));
1323 test!(fn oneshot_single_thread_peek_data() {
1324 let (tx, rx) = channel::<int>();
1325 assert_eq!(rx.try_recv(), Err(Empty))
1327 assert_eq!(rx.try_recv(), Ok(10));
1330 test!(fn oneshot_single_thread_peek_close() {
1331 let (tx, rx) = channel::<int>();
1333 assert_eq!(rx.try_recv(), Err(Disconnected));
1334 assert_eq!(rx.try_recv(), Err(Disconnected));
1337 test!(fn oneshot_single_thread_peek_open() {
1338 let (_tx, rx) = channel::<int>();
1339 assert_eq!(rx.try_recv(), Err(Empty));
1342 test!(fn oneshot_multi_task_recv_then_send() {
1343 let (tx, rx) = channel::<Box<int>>();
1345 assert!(rx.recv() == box 10);
1351 test!(fn oneshot_multi_task_recv_then_close() {
1352 let (tx, rx) = channel::<Box<int>>();
1356 let res = task::try(proc() {
1357 assert!(rx.recv() == box 10);
1359 assert!(res.is_err());
1362 test!(fn oneshot_multi_thread_close_stress() {
1363 for _ in range(0, stress_factor()) {
1364 let (tx, rx) = channel::<int>();
1372 test!(fn oneshot_multi_thread_send_close_stress() {
1373 for _ in range(0, stress_factor()) {
1374 let (tx, rx) = channel::<int>();
1378 let _ = task::try(proc() {
1384 test!(fn oneshot_multi_thread_recv_close_stress() {
1385 for _ in range(0, stress_factor()) {
1386 let (tx, rx) = channel::<int>();
1388 let res = task::try(proc() {
1391 assert!(res.is_err());
1401 test!(fn oneshot_multi_thread_send_recv_stress() {
1402 for _ in range(0, stress_factor()) {
1403 let (tx, rx) = channel();
1408 assert!(rx.recv() == box 10i);
1413 test!(fn stream_send_recv_stress() {
1414 for _ in range(0, stress_factor()) {
1415 let (tx, rx) = channel();
1420 fn send(tx: Sender<Box<int>>, i: int) {
1421 if i == 10 { return }
1429 fn recv(rx: Receiver<Box<int>>, i: int) {
1430 if i == 10 { return }
1433 assert!(rx.recv() == box i);
1440 test!(fn recv_a_lot() {
1441 // Regression test that we don't run out of stack in scheduler context
1442 let (tx, rx) = channel();
1443 for _ in range(0i, 10000) { tx.send(()); }
1444 for _ in range(0i, 10000) { rx.recv(); }
1447 test!(fn shared_chan_stress() {
1448 let (tx, rx) = channel();
1449 let total = stress_factor() + 100;
1450 for _ in range(0, total) {
1451 let tx = tx.clone();
1457 for _ in range(0, total) {
1462 test!(fn test_nested_recv_iter() {
1463 let (tx, rx) = channel::<int>();
1464 let (total_tx, total_rx) = channel::<int>();
1468 for x in rx.iter() {
1478 assert_eq!(total_rx.recv(), 6);
1481 test!(fn test_recv_iter_break() {
1482 let (tx, rx) = channel::<int>();
1483 let (count_tx, count_rx) = channel();
1487 for x in rx.iter() {
1494 count_tx.send(count);
1500 let _ = tx.send_opt(2);
1502 assert_eq!(count_rx.recv(), 4);
1505 test!(fn try_recv_states() {
1506 let (tx1, rx1) = channel::<int>();
1507 let (tx2, rx2) = channel::<()>();
1508 let (tx3, rx3) = channel::<()>();
1518 assert_eq!(rx1.try_recv(), Err(Empty));
1521 assert_eq!(rx1.try_recv(), Ok(1));
1522 assert_eq!(rx1.try_recv(), Err(Empty));
1525 assert_eq!(rx1.try_recv(), Err(Disconnected));
1528 // This bug used to end up in a livelock inside of the Receiver destructor
1529 // because the internal state of the Shared packet was corrupted
1530 test!(fn destroy_upgraded_shared_port_when_sender_still_active() {
1531 let (tx, rx) = channel();
1532 let (tx2, rx2) = channel();
1534 rx.recv(); // wait on a oneshot
1535 drop(rx); // destroy a shared
1538 // make sure the other task has gone to sleep
1539 for _ in range(0u, 5000) { task::deschedule(); }
1541 // upgrade to a shared chan and send a message
1546 // wait for the child task to exit before we exit
1550 test!(fn sends_off_the_runtime() {
1551 use std::rt::thread::Thread;
1553 let (tx, rx) = channel();
1554 let t = Thread::start(proc() {
1555 for _ in range(0u, 1000) {
1559 for _ in range(0u, 1000) {
1565 test!(fn try_recvs_off_the_runtime() {
1566 use std::rt::thread::Thread;
1568 let (tx, rx) = channel();
1569 let (cdone, pdone) = channel();
1570 let t = Thread::start(proc() {
1573 match rx.try_recv() {
1574 Ok(()) => { hits += 1; }
1575 Err(Empty) => { Thread::yield_now(); }
1576 Err(Disconnected) => return,
1581 for _ in range(0u, 10) {
1591 use std::prelude::*;
1594 pub fn stress_factor() -> uint {
1595 match os::getenv("RUST_TEST_STRESS") {
1596 Some(val) => from_str::<uint>(val.as_slice()).unwrap(),
1602 let (tx, rx) = sync_channel::<int>(1);
1604 assert_eq!(rx.recv(), 1);
1607 test!(fn drop_full() {
1608 let (tx, _rx) = sync_channel(1);
1612 test!(fn smoke_shared() {
1613 let (tx, rx) = sync_channel::<int>(1);
1615 assert_eq!(rx.recv(), 1);
1616 let tx = tx.clone();
1618 assert_eq!(rx.recv(), 1);
1621 test!(fn smoke_threads() {
1622 let (tx, rx) = sync_channel::<int>(0);
1626 assert_eq!(rx.recv(), 1);
1629 test!(fn smoke_port_gone() {
1630 let (tx, rx) = sync_channel::<int>(0);
1635 test!(fn smoke_shared_port_gone2() {
1636 let (tx, rx) = sync_channel::<int>(0);
1638 let tx2 = tx.clone();
1643 test!(fn port_gone_concurrent() {
1644 let (tx, rx) = sync_channel::<int>(0);
1651 test!(fn port_gone_concurrent_shared() {
1652 let (tx, rx) = sync_channel::<int>(0);
1653 let tx2 = tx.clone();
1663 test!(fn smoke_chan_gone() {
1664 let (tx, rx) = sync_channel::<int>(0);
1669 test!(fn smoke_chan_gone_shared() {
1670 let (tx, rx) = sync_channel::<()>(0);
1671 let tx2 = tx.clone();
1677 test!(fn chan_gone_concurrent() {
1678 let (tx, rx) = sync_channel::<int>(0);
1687 let (tx, rx) = sync_channel::<int>(0);
1689 for _ in range(0u, 10000) { tx.send(1); }
1691 for _ in range(0u, 10000) {
1692 assert_eq!(rx.recv(), 1);
1696 test!(fn stress_shared() {
1697 static AMT: uint = 1000;
1698 static NTHREADS: uint = 8;
1699 let (tx, rx) = sync_channel::<int>(0);
1700 let (dtx, drx) = sync_channel::<()>(0);
1703 for _ in range(0, AMT * NTHREADS) {
1704 assert_eq!(rx.recv(), 1);
1706 match rx.try_recv() {
1713 for _ in range(0, NTHREADS) {
1714 let tx = tx.clone();
1716 for _ in range(0, AMT) { tx.send(1); }
1723 test!(fn oneshot_single_thread_close_port_first() {
1724 // Simple test of closing without sending
1725 let (_tx, rx) = sync_channel::<int>(0);
1729 test!(fn oneshot_single_thread_close_chan_first() {
1730 // Simple test of closing without sending
1731 let (tx, _rx) = sync_channel::<int>(0);
1735 test!(fn oneshot_single_thread_send_port_close() {
1736 // Testing that the sender cleans up the payload if receiver is closed
1737 let (tx, rx) = sync_channel::<Box<int>>(0);
1742 test!(fn oneshot_single_thread_recv_chan_close() {
1743 // Receiving on a closed chan will fail
1744 let res = task::try(proc() {
1745 let (tx, rx) = sync_channel::<int>(0);
1750 assert!(res.is_err());
1753 test!(fn oneshot_single_thread_send_then_recv() {
1754 let (tx, rx) = sync_channel::<Box<int>>(1);
1756 assert!(rx.recv() == box 10);
1759 test!(fn oneshot_single_thread_try_send_open() {
1760 let (tx, rx) = sync_channel::<int>(1);
1761 assert_eq!(tx.try_send(10), Ok(()));
1762 assert!(rx.recv() == 10);
1765 test!(fn oneshot_single_thread_try_send_closed() {
1766 let (tx, rx) = sync_channel::<int>(0);
1768 assert_eq!(tx.try_send(10), Err(RecvDisconnected(10)));
1771 test!(fn oneshot_single_thread_try_send_closed2() {
1772 let (tx, _rx) = sync_channel::<int>(0);
1773 assert_eq!(tx.try_send(10), Err(Full(10)));
1776 test!(fn oneshot_single_thread_try_recv_open() {
1777 let (tx, rx) = sync_channel::<int>(1);
1779 assert!(rx.recv_opt() == Ok(10));
1782 test!(fn oneshot_single_thread_try_recv_closed() {
1783 let (tx, rx) = sync_channel::<int>(0);
1785 assert!(rx.recv_opt() == Err(()));
1788 test!(fn oneshot_single_thread_peek_data() {
1789 let (tx, rx) = sync_channel::<int>(1);
1790 assert_eq!(rx.try_recv(), Err(Empty))
1792 assert_eq!(rx.try_recv(), Ok(10));
1795 test!(fn oneshot_single_thread_peek_close() {
1796 let (tx, rx) = sync_channel::<int>(0);
1798 assert_eq!(rx.try_recv(), Err(Disconnected));
1799 assert_eq!(rx.try_recv(), Err(Disconnected));
1802 test!(fn oneshot_single_thread_peek_open() {
1803 let (_tx, rx) = sync_channel::<int>(0);
1804 assert_eq!(rx.try_recv(), Err(Empty));
1807 test!(fn oneshot_multi_task_recv_then_send() {
1808 let (tx, rx) = sync_channel::<Box<int>>(0);
1810 assert!(rx.recv() == box 10);
1816 test!(fn oneshot_multi_task_recv_then_close() {
1817 let (tx, rx) = sync_channel::<Box<int>>(0);
1821 let res = task::try(proc() {
1822 assert!(rx.recv() == box 10);
1824 assert!(res.is_err());
1827 test!(fn oneshot_multi_thread_close_stress() {
1828 for _ in range(0, stress_factor()) {
1829 let (tx, rx) = sync_channel::<int>(0);
1837 test!(fn oneshot_multi_thread_send_close_stress() {
1838 for _ in range(0, stress_factor()) {
1839 let (tx, rx) = sync_channel::<int>(0);
1843 let _ = task::try(proc() {
1849 test!(fn oneshot_multi_thread_recv_close_stress() {
1850 for _ in range(0, stress_factor()) {
1851 let (tx, rx) = sync_channel::<int>(0);
1853 let res = task::try(proc() {
1856 assert!(res.is_err());
1866 test!(fn oneshot_multi_thread_send_recv_stress() {
1867 for _ in range(0, stress_factor()) {
1868 let (tx, rx) = sync_channel::<Box<int>>(0);
1873 assert!(rx.recv() == box 10i);
1878 test!(fn stream_send_recv_stress() {
1879 for _ in range(0, stress_factor()) {
1880 let (tx, rx) = sync_channel::<Box<int>>(0);
1885 fn send(tx: SyncSender<Box<int>>, i: int) {
1886 if i == 10 { return }
1894 fn recv(rx: Receiver<Box<int>>, i: int) {
1895 if i == 10 { return }
1898 assert!(rx.recv() == box i);
1905 test!(fn recv_a_lot() {
1906 // Regression test that we don't run out of stack in scheduler context
1907 let (tx, rx) = sync_channel(10000);
1908 for _ in range(0u, 10000) { tx.send(()); }
1909 for _ in range(0u, 10000) { rx.recv(); }
1912 test!(fn shared_chan_stress() {
1913 let (tx, rx) = sync_channel(0);
1914 let total = stress_factor() + 100;
1915 for _ in range(0, total) {
1916 let tx = tx.clone();
1922 for _ in range(0, total) {
1927 test!(fn test_nested_recv_iter() {
1928 let (tx, rx) = sync_channel::<int>(0);
1929 let (total_tx, total_rx) = sync_channel::<int>(0);
1933 for x in rx.iter() {
1943 assert_eq!(total_rx.recv(), 6);
1946 test!(fn test_recv_iter_break() {
1947 let (tx, rx) = sync_channel::<int>(0);
1948 let (count_tx, count_rx) = sync_channel(0);
1952 for x in rx.iter() {
1959 count_tx.send(count);
1965 let _ = tx.try_send(2);
1967 assert_eq!(count_rx.recv(), 4);
1970 test!(fn try_recv_states() {
1971 let (tx1, rx1) = sync_channel::<int>(1);
1972 let (tx2, rx2) = sync_channel::<()>(1);
1973 let (tx3, rx3) = sync_channel::<()>(1);
1983 assert_eq!(rx1.try_recv(), Err(Empty));
1986 assert_eq!(rx1.try_recv(), Ok(1));
1987 assert_eq!(rx1.try_recv(), Err(Empty));
1990 assert_eq!(rx1.try_recv(), Err(Disconnected));
1993 // This bug used to end up in a livelock inside of the Receiver destructor
1994 // because the internal state of the Shared packet was corrupted
1995 test!(fn destroy_upgraded_shared_port_when_sender_still_active() {
1996 let (tx, rx) = sync_channel::<()>(0);
1997 let (tx2, rx2) = sync_channel::<()>(0);
1999 rx.recv(); // wait on a oneshot
2000 drop(rx); // destroy a shared
2003 // make sure the other task has gone to sleep
2004 for _ in range(0u, 5000) { task::deschedule(); }
2006 // upgrade to a shared chan and send a message
2011 // wait for the child task to exit before we exit
2015 test!(fn try_recvs_off_the_runtime() {
2016 use std::rt::thread::Thread;
2018 let (tx, rx) = sync_channel::<()>(0);
2019 let (cdone, pdone) = channel();
2020 let t = Thread::start(proc() {
2023 match rx.try_recv() {
2024 Ok(()) => { hits += 1; }
2025 Err(Empty) => { Thread::yield_now(); }
2026 Err(Disconnected) => return,
2031 for _ in range(0u, 10) {
2038 test!(fn send_opt1() {
2039 let (tx, rx) = sync_channel::<int>(0);
2040 spawn(proc() { rx.recv(); });
2041 assert_eq!(tx.send_opt(1), Ok(()));
2044 test!(fn send_opt2() {
2045 let (tx, rx) = sync_channel::<int>(0);
2046 spawn(proc() { drop(rx); });
2047 assert_eq!(tx.send_opt(1), Err(1));
2050 test!(fn send_opt3() {
2051 let (tx, rx) = sync_channel::<int>(1);
2052 assert_eq!(tx.send_opt(1), Ok(()));
2053 spawn(proc() { drop(rx); });
2054 assert_eq!(tx.send_opt(1), Err(1));
2057 test!(fn send_opt4() {
2058 let (tx, rx) = sync_channel::<int>(0);
2059 let tx2 = tx.clone();
2060 let (done, donerx) = channel();
2061 let done2 = done.clone();
2063 assert_eq!(tx.send_opt(1), Err(1));
2067 assert_eq!(tx2.send_opt(2), Err(2));
2075 test!(fn try_send1() {
2076 let (tx, _rx) = sync_channel::<int>(0);
2077 assert_eq!(tx.try_send(1), Err(Full(1)));
2080 test!(fn try_send2() {
2081 let (tx, _rx) = sync_channel::<int>(1);
2082 assert_eq!(tx.try_send(1), Ok(()));
2083 assert_eq!(tx.try_send(1), Err(Full(1)));
2086 test!(fn try_send3() {
2087 let (tx, rx) = sync_channel::<int>(1);
2088 assert_eq!(tx.try_send(1), Ok(()));
2090 assert_eq!(tx.try_send(1), Err(RecvDisconnected(1)));
2093 test!(fn try_send4() {
2094 let (tx, rx) = sync_channel::<int>(0);
2096 for _ in range(0u, 1000) { task::deschedule(); }
2097 assert_eq!(tx.try_send(1), Ok(()));
2099 assert_eq!(rx.recv(), 1);
2100 } #[ignore(reason = "flaky on libnative")])