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::*;
44 use sync::atomic::{Ordering, AtomicUint};
45 use sync::mpsc::blocking::{self, WaitToken, SignalToken};
46 use sync::mpsc::select::StartResult::{self, Installed, Abort};
47 use sync::{Mutex, MutexGuard};
49 pub struct Packet<T> {
50 /// Only field outside of the mutex. Just done for kicks, but mainly because
51 /// the other shared channel already had the code implemented
54 lock: Mutex<State<T>>,
57 unsafe impl<T:Send> Send for Packet<T> { }
59 unsafe impl<T:Send> Sync for Packet<T> { }
62 disconnected: bool, // Is the channel disconnected yet?
63 queue: Queue, // queue of senders waiting to send data
64 blocker: Blocker, // currently blocked task on this channel
65 buf: Buffer<T>, // storage for buffered messages
66 cap: uint, // capacity of this channel
68 /// A curious flag used to indicate whether a sender failed or succeeded in
69 /// blocking. This is used to transmit information back to the task that it
70 /// must dequeue its message from the buffer because it was not received.
71 /// This is only relevant in the 0-buffer case. This obviously cannot be
72 /// safely constructed, but it's guaranteed to always have a valid pointer
74 canceled: Option<&'static mut bool>,
77 unsafe impl<T: Send> Send for State<T> {}
79 /// Possible flavors of threads who can be blocked on this channel.
81 BlockedSender(SignalToken),
82 BlockedReceiver(SignalToken),
86 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
87 /// this structure is not safe at all
94 token: Option<SignalToken>,
98 unsafe impl Send for Node {}
100 /// A simple ring-buffer
113 /// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
114 /// in the meantime. This re-locks the mutex upon returning.
115 fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
116 mut guard: MutexGuard<'b, State<T>>,
117 f: fn(SignalToken) -> Blocker)
118 -> MutexGuard<'a, State<T>>
120 let (wait_token, signal_token) = blocking::tokens();
121 match mem::replace(&mut guard.blocker, f(signal_token)) {
125 drop(guard); // unlock
126 wait_token.wait(); // block
127 lock.lock().unwrap() // relock
130 /// Wakes up a thread, dropping the lock at the correct time
131 fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
132 // We need to be careful to wake up the waiting task *outside* of the mutex
133 // in case it incurs a context switch.
138 impl<T: Send> Packet<T> {
139 pub fn new(cap: uint) -> Packet<T> {
141 channels: AtomicUint::new(1),
142 lock: Mutex::new(State {
144 blocker: NoneBlocked,
148 head: 0 as *mut Node,
149 tail: 0 as *mut Node,
152 buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
160 // wait until a send slot is available, returning locked access to
161 // the channel state.
162 fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
163 let mut node = Node { token: None, next: 0 as *mut Node };
165 let mut guard = self.lock.lock().unwrap();
166 // are we ready to go?
167 if guard.disconnected || guard.buf.size() < guard.buf.cap() {
170 // no room; actually block
171 let wait_token = guard.queue.enqueue(&mut node);
177 pub fn send(&self, t: T) -> Result<(), T> {
178 let mut guard = self.acquire_send_slot();
179 if guard.disconnected { return Err(t) }
180 guard.buf.enqueue(t);
182 match mem::replace(&mut guard.blocker, NoneBlocked) {
183 // if our capacity is 0, then we need to wait for a receiver to be
184 // available to take our data. After waiting, we check again to make
185 // sure the port didn't go away in the meantime. If it did, we need
186 // to hand back our data.
187 NoneBlocked if guard.cap == 0 => {
188 let mut canceled = false;
189 assert!(guard.canceled.is_none());
190 guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
191 let mut guard = wait(&self.lock, guard, BlockedSender);
192 if canceled {Err(guard.buf.dequeue())} else {Ok(())}
195 // success, we buffered some data
196 NoneBlocked => Ok(()),
198 // success, someone's about to receive our buffered data.
199 BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
201 BlockedSender(..) => panic!("lolwut"),
205 pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
206 let mut guard = self.lock.lock().unwrap();
207 if guard.disconnected {
208 Err(super::TrySendError::Disconnected(t))
209 } else if guard.buf.size() == guard.buf.cap() {
210 Err(super::TrySendError::Full(t))
211 } else if guard.cap == 0 {
212 // With capacity 0, even though we have buffer space we can't
213 // transfer the data unless there's a receiver waiting.
214 match mem::replace(&mut guard.blocker, NoneBlocked) {
215 NoneBlocked => Err(super::TrySendError::Full(t)),
216 BlockedSender(..) => unreachable!(),
217 BlockedReceiver(token) => {
218 guard.buf.enqueue(t);
219 wakeup(token, guard);
224 // If the buffer has some space and the capacity isn't 0, then we
225 // just enqueue the data for later retrieval, ensuring to wake up
226 // any blocked receiver if there is one.
227 assert!(guard.buf.size() < guard.buf.cap());
228 guard.buf.enqueue(t);
229 match mem::replace(&mut guard.blocker, NoneBlocked) {
230 BlockedReceiver(token) => wakeup(token, guard),
232 BlockedSender(..) => unreachable!(),
238 // Receives a message from this channel
240 // When reading this, remember that there can only ever be one receiver at
242 pub fn recv(&self) -> Result<T, ()> {
243 let mut guard = self.lock.lock().unwrap();
245 // Wait for the buffer to have something in it. No need for a while loop
246 // because we're the only receiver.
247 let mut waited = false;
248 if !guard.disconnected && guard.buf.size() == 0 {
249 guard = wait(&self.lock, guard, BlockedReceiver);
252 if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
254 // Pick up the data, wake up our neighbors, and carry on
255 assert!(guard.buf.size() > 0);
256 let ret = guard.buf.dequeue();
257 self.wakeup_senders(waited, guard);
261 pub fn try_recv(&self) -> Result<T, Failure> {
262 let mut guard = self.lock.lock().unwrap();
265 if guard.disconnected { return Err(Disconnected) }
266 if guard.buf.size() == 0 { return Err(Empty) }
268 // Be sure to wake up neighbors
269 let ret = Ok(guard.buf.dequeue());
270 self.wakeup_senders(false, guard);
275 // Wake up pending senders after some data has been received
277 // * `waited` - flag if the receiver blocked to receive some data, or if it
278 // just picked up some data on the way out
279 // * `guard` - the lock guard that is held over this channel's lock
280 fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
281 let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
283 // If this is a no-buffer channel (cap == 0), then if we didn't wait we
284 // need to ACK the sender. If we waited, then the sender waking us up
285 // was already the ACK.
286 let pending_sender2 = if guard.cap == 0 && !waited {
287 match mem::replace(&mut guard.blocker, NoneBlocked) {
289 BlockedReceiver(..) => unreachable!(),
290 BlockedSender(token) => {
291 guard.canceled.take();
300 // only outside of the lock do we wake up the pending tasks
301 pending_sender1.map(|t| t.signal());
302 pending_sender2.map(|t| t.signal());
305 // Prepares this shared packet for a channel clone, essentially just bumping
307 pub fn clone_chan(&self) {
308 self.channels.fetch_add(1, Ordering::SeqCst);
311 pub fn drop_chan(&self) {
312 // Only flag the channel as disconnected if we're the last channel
313 match self.channels.fetch_sub(1, Ordering::SeqCst) {
318 // Not much to do other than wake up a receiver if one's there
319 let mut guard = self.lock.lock().unwrap();
320 if guard.disconnected { return }
321 guard.disconnected = true;
322 match mem::replace(&mut guard.blocker, NoneBlocked) {
324 BlockedSender(..) => unreachable!(),
325 BlockedReceiver(token) => wakeup(token, guard),
329 pub fn drop_port(&self) {
330 let mut guard = self.lock.lock().unwrap();
332 if guard.disconnected { return }
333 guard.disconnected = true;
335 // If the capacity is 0, then the sender may want its data back after
336 // we're disconnected. Otherwise it's now our responsibility to destroy
337 // the buffered data. As with many other portions of this code, this
338 // needs to be careful to destroy the data *outside* of the lock to
340 let _data = if guard.cap != 0 {
341 mem::replace(&mut guard.buf.buf, Vec::new())
345 let mut queue = mem::replace(&mut guard.queue, Queue {
346 head: 0 as *mut Node,
347 tail: 0 as *mut Node,
350 let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
352 BlockedSender(token) => {
353 *guard.canceled.take().unwrap() = true;
356 BlockedReceiver(..) => unreachable!(),
361 match queue.dequeue() {
362 Some(token) => { token.signal(); }
366 waiter.map(|t| t.signal());
369 ////////////////////////////////////////////////////////////////////////////
370 // select implementation
371 ////////////////////////////////////////////////////////////////////////////
373 // If Ok, the value is whether this port has data, if Err, then the upgraded
374 // port needs to be checked instead of this one.
375 pub fn can_recv(&self) -> bool {
376 let guard = self.lock.lock().unwrap();
377 guard.disconnected || guard.buf.size() > 0
380 // Attempts to start selection on this port. This can either succeed or fail
381 // because there is data waiting.
382 pub fn start_selection(&self, token: SignalToken) -> StartResult {
383 let mut guard = self.lock.lock().unwrap();
384 if guard.disconnected || guard.buf.size() > 0 {
387 match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
389 BlockedSender(..) => unreachable!(),
390 BlockedReceiver(..) => unreachable!(),
396 // Remove a previous selecting task from this port. This ensures that the
397 // blocked task will no longer be visible to any other threads.
399 // The return value indicates whether there's data on this port.
400 pub fn abort_selection(&self) -> bool {
401 let mut guard = self.lock.lock().unwrap();
402 match mem::replace(&mut guard.blocker, NoneBlocked) {
404 BlockedSender(token) => {
405 guard.blocker = BlockedSender(token);
408 BlockedReceiver(token) => { drop(token); false }
414 impl<T: Send> Drop for Packet<T> {
416 assert_eq!(self.channels.load(Ordering::SeqCst), 0);
417 let mut guard = self.lock.lock().unwrap();
418 assert!(guard.queue.dequeue().is_none());
419 assert!(guard.canceled.is_none());
424 ////////////////////////////////////////////////////////////////////////////////
425 // Buffer, a simple ring buffer backed by Vec<T>
426 ////////////////////////////////////////////////////////////////////////////////
429 fn enqueue(&mut self, t: T) {
430 let pos = (self.start + self.size) % self.buf.len();
432 let prev = mem::replace(&mut self.buf[pos], Some(t));
433 assert!(prev.is_none());
436 fn dequeue(&mut self) -> T {
437 let start = self.start;
439 self.start = (self.start + 1) % self.buf.len();
440 self.buf[start].take().unwrap()
443 fn size(&self) -> uint { self.size }
444 fn cap(&self) -> uint { self.buf.len() }
447 ////////////////////////////////////////////////////////////////////////////////
448 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
449 ////////////////////////////////////////////////////////////////////////////////
452 fn enqueue(&mut self, node: &mut Node) -> WaitToken {
453 let (wait_token, signal_token) = blocking::tokens();
454 node.token = Some(signal_token);
455 node.next = 0 as *mut Node;
457 if self.tail.is_null() {
458 self.head = node as *mut Node;
459 self.tail = node as *mut Node;
462 (*self.tail).next = node as *mut Node;
463 self.tail = node as *mut Node;
470 fn dequeue(&mut self) -> Option<SignalToken> {
471 if self.head.is_null() {
474 let node = self.head;
475 self.head = unsafe { (*node).next };
476 if self.head.is_null() {
477 self.tail = 0 as *mut Node;
480 (*node).next = 0 as *mut Node;
481 Some((*node).token.take().unwrap())