1 // Copyright 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 /// Synchronous channels/ports
13 /// This channel implementation differs significantly from the asynchronous
14 /// implementations found next to it (oneshot/stream/share). This is an
15 /// implementation of a synchronous, bounded buffer channel.
17 /// Each channel is created with some amount of backing buffer, and sends will
18 /// *block* until buffer space becomes available. A buffer size of 0 is valid,
19 /// which means that every successful send is paired with a successful recv.
21 /// This flavor of channels defines a new `send_opt` method for channels which
22 /// is the method by which a message is sent but the task does not panic if it
23 /// cannot be delivered.
25 /// Another major difference is that send() will *always* return back the data
26 /// if it couldn't be sent. This is because it is deterministically known when
27 /// the data is received and when it is not received.
29 /// Implementation-wise, it can all be summed up with "use a mutex plus some
30 /// logic". The mutex used here is an OS native mutex, meaning that no user code
31 /// is run inside of the mutex (to prevent context switching). This
32 /// implementation shares almost all code for the buffered and unbuffered cases
33 /// of a synchronous channel. There are a few branches for the unbuffered case,
34 /// but they're mostly just relevant to blocking senders.
38 pub use self::Failure::*;
45 use sync::atomic::{Ordering, AtomicUsize};
46 use sync::mpsc::blocking::{self, WaitToken, SignalToken};
47 use sync::mpsc::select::StartResult::{self, Installed, Abort};
48 use sync::{Mutex, MutexGuard};
50 pub struct Packet<T> {
51 /// Only field outside of the mutex. Just done for kicks, but mainly because
52 /// the other shared channel already had the code implemented
53 channels: AtomicUsize,
55 lock: Mutex<State<T>>,
58 unsafe impl<T:Send> Send for Packet<T> { }
60 unsafe impl<T:Send> Sync for Packet<T> { }
63 disconnected: bool, // Is the channel disconnected yet?
64 queue: Queue, // queue of senders waiting to send data
65 blocker: Blocker, // currently blocked task on this channel
66 buf: Buffer<T>, // storage for buffered messages
67 cap: uint, // capacity of this channel
69 /// A curious flag used to indicate whether a sender failed or succeeded in
70 /// blocking. This is used to transmit information back to the task that it
71 /// must dequeue its message from the buffer because it was not received.
72 /// This is only relevant in the 0-buffer case. This obviously cannot be
73 /// safely constructed, but it's guaranteed to always have a valid pointer
75 canceled: Option<&'static mut bool>,
78 unsafe impl<T: Send> Send for State<T> {}
80 /// Possible flavors of threads who can be blocked on this channel.
82 BlockedSender(SignalToken),
83 BlockedReceiver(SignalToken),
87 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
88 /// this structure is not safe at all
95 token: Option<SignalToken>,
99 unsafe impl Send for Node {}
101 /// A simple ring-buffer
114 /// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
115 /// in the meantime. This re-locks the mutex upon returning.
116 fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
117 mut guard: MutexGuard<'b, State<T>>,
118 f: fn(SignalToken) -> Blocker)
119 -> MutexGuard<'a, State<T>>
121 let (wait_token, signal_token) = blocking::tokens();
122 match mem::replace(&mut guard.blocker, f(signal_token)) {
126 drop(guard); // unlock
127 wait_token.wait(); // block
128 lock.lock().unwrap() // relock
131 /// Wakes up a thread, dropping the lock at the correct time
132 fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
133 // We need to be careful to wake up the waiting task *outside* of the mutex
134 // in case it incurs a context switch.
139 impl<T: Send> Packet<T> {
140 pub fn new(cap: uint) -> Packet<T> {
142 channels: AtomicUsize::new(1),
143 lock: Mutex::new(State {
145 blocker: NoneBlocked,
149 head: ptr::null_mut(),
150 tail: ptr::null_mut(),
153 buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
161 // wait until a send slot is available, returning locked access to
162 // the channel state.
163 fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
164 let mut node = Node { token: None, next: ptr::null_mut() };
166 let mut guard = self.lock.lock().unwrap();
167 // are we ready to go?
168 if guard.disconnected || guard.buf.size() < guard.buf.cap() {
171 // no room; actually block
172 let wait_token = guard.queue.enqueue(&mut node);
178 pub fn send(&self, t: T) -> Result<(), T> {
179 let mut guard = self.acquire_send_slot();
180 if guard.disconnected { return Err(t) }
181 guard.buf.enqueue(t);
183 match mem::replace(&mut guard.blocker, NoneBlocked) {
184 // if our capacity is 0, then we need to wait for a receiver to be
185 // available to take our data. After waiting, we check again to make
186 // sure the port didn't go away in the meantime. If it did, we need
187 // to hand back our data.
188 NoneBlocked if guard.cap == 0 => {
189 let mut canceled = false;
190 assert!(guard.canceled.is_none());
191 guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
192 let mut guard = wait(&self.lock, guard, BlockedSender);
193 if canceled {Err(guard.buf.dequeue())} else {Ok(())}
196 // success, we buffered some data
197 NoneBlocked => Ok(()),
199 // success, someone's about to receive our buffered data.
200 BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
202 BlockedSender(..) => panic!("lolwut"),
206 pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
207 let mut guard = self.lock.lock().unwrap();
208 if guard.disconnected {
209 Err(super::TrySendError::Disconnected(t))
210 } else if guard.buf.size() == guard.buf.cap() {
211 Err(super::TrySendError::Full(t))
212 } else if guard.cap == 0 {
213 // With capacity 0, even though we have buffer space we can't
214 // transfer the data unless there's a receiver waiting.
215 match mem::replace(&mut guard.blocker, NoneBlocked) {
216 NoneBlocked => Err(super::TrySendError::Full(t)),
217 BlockedSender(..) => unreachable!(),
218 BlockedReceiver(token) => {
219 guard.buf.enqueue(t);
220 wakeup(token, guard);
225 // If the buffer has some space and the capacity isn't 0, then we
226 // just enqueue the data for later retrieval, ensuring to wake up
227 // any blocked receiver if there is one.
228 assert!(guard.buf.size() < guard.buf.cap());
229 guard.buf.enqueue(t);
230 match mem::replace(&mut guard.blocker, NoneBlocked) {
231 BlockedReceiver(token) => wakeup(token, guard),
233 BlockedSender(..) => unreachable!(),
239 // Receives a message from this channel
241 // When reading this, remember that there can only ever be one receiver at
243 pub fn recv(&self) -> Result<T, ()> {
244 let mut guard = self.lock.lock().unwrap();
246 // Wait for the buffer to have something in it. No need for a while loop
247 // because we're the only receiver.
248 let mut waited = false;
249 if !guard.disconnected && guard.buf.size() == 0 {
250 guard = wait(&self.lock, guard, BlockedReceiver);
253 if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
255 // Pick up the data, wake up our neighbors, and carry on
256 assert!(guard.buf.size() > 0);
257 let ret = guard.buf.dequeue();
258 self.wakeup_senders(waited, guard);
262 pub fn try_recv(&self) -> Result<T, Failure> {
263 let mut guard = self.lock.lock().unwrap();
266 if guard.disconnected { return Err(Disconnected) }
267 if guard.buf.size() == 0 { return Err(Empty) }
269 // Be sure to wake up neighbors
270 let ret = Ok(guard.buf.dequeue());
271 self.wakeup_senders(false, guard);
276 // Wake up pending senders after some data has been received
278 // * `waited` - flag if the receiver blocked to receive some data, or if it
279 // just picked up some data on the way out
280 // * `guard` - the lock guard that is held over this channel's lock
281 fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
282 let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
284 // If this is a no-buffer channel (cap == 0), then if we didn't wait we
285 // need to ACK the sender. If we waited, then the sender waking us up
286 // was already the ACK.
287 let pending_sender2 = if guard.cap == 0 && !waited {
288 match mem::replace(&mut guard.blocker, NoneBlocked) {
290 BlockedReceiver(..) => unreachable!(),
291 BlockedSender(token) => {
292 guard.canceled.take();
301 // only outside of the lock do we wake up the pending tasks
302 pending_sender1.map(|t| t.signal());
303 pending_sender2.map(|t| t.signal());
306 // Prepares this shared packet for a channel clone, essentially just bumping
308 pub fn clone_chan(&self) {
309 self.channels.fetch_add(1, Ordering::SeqCst);
312 pub fn drop_chan(&self) {
313 // Only flag the channel as disconnected if we're the last channel
314 match self.channels.fetch_sub(1, Ordering::SeqCst) {
319 // Not much to do other than wake up a receiver if one's there
320 let mut guard = self.lock.lock().unwrap();
321 if guard.disconnected { return }
322 guard.disconnected = true;
323 match mem::replace(&mut guard.blocker, NoneBlocked) {
325 BlockedSender(..) => unreachable!(),
326 BlockedReceiver(token) => wakeup(token, guard),
330 pub fn drop_port(&self) {
331 let mut guard = self.lock.lock().unwrap();
333 if guard.disconnected { return }
334 guard.disconnected = true;
336 // If the capacity is 0, then the sender may want its data back after
337 // we're disconnected. Otherwise it's now our responsibility to destroy
338 // the buffered data. As with many other portions of this code, this
339 // needs to be careful to destroy the data *outside* of the lock to
341 let _data = if guard.cap != 0 {
342 mem::replace(&mut guard.buf.buf, Vec::new())
346 let mut queue = mem::replace(&mut guard.queue, Queue {
347 head: ptr::null_mut(),
348 tail: ptr::null_mut(),
351 let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
353 BlockedSender(token) => {
354 *guard.canceled.take().unwrap() = true;
357 BlockedReceiver(..) => unreachable!(),
362 match queue.dequeue() {
363 Some(token) => { token.signal(); }
367 waiter.map(|t| t.signal());
370 ////////////////////////////////////////////////////////////////////////////
371 // select implementation
372 ////////////////////////////////////////////////////////////////////////////
374 // If Ok, the value is whether this port has data, if Err, then the upgraded
375 // port needs to be checked instead of this one.
376 pub fn can_recv(&self) -> bool {
377 let guard = self.lock.lock().unwrap();
378 guard.disconnected || guard.buf.size() > 0
381 // Attempts to start selection on this port. This can either succeed or fail
382 // because there is data waiting.
383 pub fn start_selection(&self, token: SignalToken) -> StartResult {
384 let mut guard = self.lock.lock().unwrap();
385 if guard.disconnected || guard.buf.size() > 0 {
388 match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
390 BlockedSender(..) => unreachable!(),
391 BlockedReceiver(..) => unreachable!(),
397 // Remove a previous selecting task from this port. This ensures that the
398 // blocked task will no longer be visible to any other threads.
400 // The return value indicates whether there's data on this port.
401 pub fn abort_selection(&self) -> bool {
402 let mut guard = self.lock.lock().unwrap();
403 match mem::replace(&mut guard.blocker, NoneBlocked) {
405 BlockedSender(token) => {
406 guard.blocker = BlockedSender(token);
409 BlockedReceiver(token) => { drop(token); false }
415 impl<T: Send> Drop for Packet<T> {
417 assert_eq!(self.channels.load(Ordering::SeqCst), 0);
418 let mut guard = self.lock.lock().unwrap();
419 assert!(guard.queue.dequeue().is_none());
420 assert!(guard.canceled.is_none());
425 ////////////////////////////////////////////////////////////////////////////////
426 // Buffer, a simple ring buffer backed by Vec<T>
427 ////////////////////////////////////////////////////////////////////////////////
430 fn enqueue(&mut self, t: T) {
431 let pos = (self.start + self.size) % self.buf.len();
433 let prev = mem::replace(&mut self.buf[pos], Some(t));
434 assert!(prev.is_none());
437 fn dequeue(&mut self) -> T {
438 let start = self.start;
440 self.start = (self.start + 1) % self.buf.len();
441 let result = &mut self.buf[start];
442 result.take().unwrap()
445 fn size(&self) -> uint { self.size }
446 fn cap(&self) -> uint { self.buf.len() }
449 ////////////////////////////////////////////////////////////////////////////////
450 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
451 ////////////////////////////////////////////////////////////////////////////////
454 fn enqueue(&mut self, node: &mut Node) -> WaitToken {
455 let (wait_token, signal_token) = blocking::tokens();
456 node.token = Some(signal_token);
457 node.next = ptr::null_mut();
459 if self.tail.is_null() {
460 self.head = node as *mut Node;
461 self.tail = node as *mut Node;
464 (*self.tail).next = node as *mut Node;
465 self.tail = node as *mut Node;
472 fn dequeue(&mut self) -> Option<SignalToken> {
473 if self.head.is_null() {
476 let node = self.head;
477 self.head = unsafe { (*node).next };
478 if self.head.is_null() {
479 self.tail = ptr::null_mut();
482 (*node).next = ptr::null_mut();
483 Some((*node).token.take().unwrap())