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, Mutex, MutexGuard};
45 use sync::mpsc::blocking::{mod, WaitToken, SignalToken};
46 use sync::mpsc::select::StartResult::{mod, Installed, Abort};
48 pub struct Packet<T> {
49 /// Only field outside of the mutex. Just done for kicks, but mainly because
50 /// the other shared channel already had the code implemented
51 channels: atomic::AtomicUint,
53 lock: Mutex<State<T>>,
56 unsafe impl<T:Send> Send for Packet<T> { }
58 unsafe impl<T:Send> Sync for Packet<T> { }
61 disconnected: bool, // Is the channel disconnected yet?
62 queue: Queue, // queue of senders waiting to send data
63 blocker: Blocker, // currently blocked task on this channel
64 buf: Buffer<T>, // storage for buffered messages
65 cap: uint, // capacity of this channel
67 /// A curious flag used to indicate whether a sender failed or succeeded in
68 /// blocking. This is used to transmit information back to the task that it
69 /// must dequeue its message from the buffer because it was not received.
70 /// This is only relevant in the 0-buffer case. This obviously cannot be
71 /// safely constructed, but it's guaranteed to always have a valid pointer
73 canceled: Option<&'static mut bool>,
76 unsafe impl<T: Send> Send for State<T> {}
78 /// Possible flavors of threads who can be blocked on this channel.
80 BlockedSender(SignalToken),
81 BlockedReceiver(SignalToken),
85 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
86 /// this structure is not safe at all
93 token: Option<SignalToken>,
97 unsafe impl Send for Node {}
99 /// A simple ring-buffer
112 /// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
113 /// in the meantime. This re-locks the mutex upon returning.
114 fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
115 mut guard: MutexGuard<'b, State<T>>,
116 f: fn(SignalToken) -> Blocker)
117 -> MutexGuard<'a, State<T>>
119 let (wait_token, signal_token) = blocking::tokens();
120 match mem::replace(&mut guard.blocker, f(signal_token)) {
124 drop(guard); // unlock
125 wait_token.wait(); // block
126 lock.lock().unwrap() // relock
129 /// Wakes up a thread, dropping the lock at the correct time
130 fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
131 // We need to be careful to wake up the waiting task *outside* of the mutex
132 // in case it incurs a context switch.
137 impl<T: Send> Packet<T> {
138 pub fn new(cap: uint) -> Packet<T> {
140 channels: atomic::AtomicUint::new(1),
141 lock: Mutex::new(State {
143 blocker: NoneBlocked,
147 head: 0 as *mut Node,
148 tail: 0 as *mut Node,
151 buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
159 // wait until a send slot is available, returning locked access to
160 // the channel state.
161 fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
162 let mut node = Node { token: None, next: 0 as *mut Node };
164 let mut guard = self.lock.lock().unwrap();
165 // are we ready to go?
166 if guard.disconnected || guard.buf.size() < guard.buf.cap() {
169 // no room; actually block
170 let wait_token = guard.queue.enqueue(&mut node);
176 pub fn send(&self, t: T) -> Result<(), T> {
177 let mut guard = self.acquire_send_slot();
178 if guard.disconnected { return Err(t) }
179 guard.buf.enqueue(t);
181 match mem::replace(&mut guard.blocker, NoneBlocked) {
182 // if our capacity is 0, then we need to wait for a receiver to be
183 // available to take our data. After waiting, we check again to make
184 // sure the port didn't go away in the meantime. If it did, we need
185 // to hand back our data.
186 NoneBlocked if guard.cap == 0 => {
187 let mut canceled = false;
188 assert!(guard.canceled.is_none());
189 guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
190 let mut guard = wait(&self.lock, guard, BlockedSender);
191 if canceled {Err(guard.buf.dequeue())} else {Ok(())}
194 // success, we buffered some data
195 NoneBlocked => Ok(()),
197 // success, someone's about to receive our buffered data.
198 BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
200 BlockedSender(..) => panic!("lolwut"),
204 pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
205 let mut guard = self.lock.lock().unwrap();
206 if guard.disconnected {
207 Err(super::TrySendError::Disconnected(t))
208 } else if guard.buf.size() == guard.buf.cap() {
209 Err(super::TrySendError::Full(t))
210 } else if guard.cap == 0 {
211 // With capacity 0, even though we have buffer space we can't
212 // transfer the data unless there's a receiver waiting.
213 match mem::replace(&mut guard.blocker, NoneBlocked) {
214 NoneBlocked => Err(super::TrySendError::Full(t)),
215 BlockedSender(..) => unreachable!(),
216 BlockedReceiver(token) => {
217 guard.buf.enqueue(t);
218 wakeup(token, guard);
223 // If the buffer has some space and the capacity isn't 0, then we
224 // just enqueue the data for later retrieval, ensuring to wake up
225 // any blocked receiver if there is one.
226 assert!(guard.buf.size() < guard.buf.cap());
227 guard.buf.enqueue(t);
228 match mem::replace(&mut guard.blocker, NoneBlocked) {
229 BlockedReceiver(token) => wakeup(token, guard),
231 BlockedSender(..) => unreachable!(),
237 // Receives a message from this channel
239 // When reading this, remember that there can only ever be one receiver at
241 pub fn recv(&self) -> Result<T, ()> {
242 let mut guard = self.lock.lock().unwrap();
244 // Wait for the buffer to have something in it. No need for a while loop
245 // because we're the only receiver.
246 let mut waited = false;
247 if !guard.disconnected && guard.buf.size() == 0 {
248 guard = wait(&self.lock, guard, BlockedReceiver);
251 if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
253 // Pick up the data, wake up our neighbors, and carry on
254 assert!(guard.buf.size() > 0);
255 let ret = guard.buf.dequeue();
256 self.wakeup_senders(waited, guard);
260 pub fn try_recv(&self) -> Result<T, Failure> {
261 let mut guard = self.lock.lock().unwrap();
264 if guard.disconnected { return Err(Disconnected) }
265 if guard.buf.size() == 0 { return Err(Empty) }
267 // Be sure to wake up neighbors
268 let ret = Ok(guard.buf.dequeue());
269 self.wakeup_senders(false, guard);
274 // Wake up pending senders after some data has been received
276 // * `waited` - flag if the receiver blocked to receive some data, or if it
277 // just picked up some data on the way out
278 // * `guard` - the lock guard that is held over this channel's lock
279 fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
280 let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
282 // If this is a no-buffer channel (cap == 0), then if we didn't wait we
283 // need to ACK the sender. If we waited, then the sender waking us up
284 // was already the ACK.
285 let pending_sender2 = if guard.cap == 0 && !waited {
286 match mem::replace(&mut guard.blocker, NoneBlocked) {
288 BlockedReceiver(..) => unreachable!(),
289 BlockedSender(token) => {
290 guard.canceled.take();
299 // only outside of the lock do we wake up the pending tasks
300 pending_sender1.map(|t| t.signal());
301 pending_sender2.map(|t| t.signal());
304 // Prepares this shared packet for a channel clone, essentially just bumping
306 pub fn clone_chan(&self) {
307 self.channels.fetch_add(1, atomic::SeqCst);
310 pub fn drop_chan(&self) {
311 // Only flag the channel as disconnected if we're the last channel
312 match self.channels.fetch_sub(1, atomic::SeqCst) {
317 // Not much to do other than wake up a receiver if one's there
318 let mut guard = self.lock.lock().unwrap();
319 if guard.disconnected { return }
320 guard.disconnected = true;
321 match mem::replace(&mut guard.blocker, NoneBlocked) {
323 BlockedSender(..) => unreachable!(),
324 BlockedReceiver(token) => wakeup(token, guard),
328 pub fn drop_port(&self) {
329 let mut guard = self.lock.lock().unwrap();
331 if guard.disconnected { return }
332 guard.disconnected = true;
334 // If the capacity is 0, then the sender may want its data back after
335 // we're disconnected. Otherwise it's now our responsibility to destroy
336 // the buffered data. As with many other portions of this code, this
337 // needs to be careful to destroy the data *outside* of the lock to
339 let _data = if guard.cap != 0 {
340 mem::replace(&mut guard.buf.buf, Vec::new())
344 let mut queue = mem::replace(&mut guard.queue, Queue {
345 head: 0 as *mut Node,
346 tail: 0 as *mut Node,
349 let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
351 BlockedSender(token) => {
352 *guard.canceled.take().unwrap() = true;
355 BlockedReceiver(..) => unreachable!(),
360 match queue.dequeue() {
361 Some(token) => { token.signal(); }
365 waiter.map(|t| t.signal());
368 ////////////////////////////////////////////////////////////////////////////
369 // select implementation
370 ////////////////////////////////////////////////////////////////////////////
372 // If Ok, the value is whether this port has data, if Err, then the upgraded
373 // port needs to be checked instead of this one.
374 pub fn can_recv(&self) -> bool {
375 let guard = self.lock.lock().unwrap();
376 guard.disconnected || guard.buf.size() > 0
379 // Attempts to start selection on this port. This can either succeed or fail
380 // because there is data waiting.
381 pub fn start_selection(&self, token: SignalToken) -> StartResult {
382 let mut guard = self.lock.lock().unwrap();
383 if guard.disconnected || guard.buf.size() > 0 {
386 match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
388 BlockedSender(..) => unreachable!(),
389 BlockedReceiver(..) => unreachable!(),
395 // Remove a previous selecting task from this port. This ensures that the
396 // blocked task will no longer be visible to any other threads.
398 // The return value indicates whether there's data on this port.
399 pub fn abort_selection(&self) -> bool {
400 let mut guard = self.lock.lock().unwrap();
401 match mem::replace(&mut guard.blocker, NoneBlocked) {
403 BlockedSender(token) => {
404 guard.blocker = BlockedSender(token);
407 BlockedReceiver(token) => { drop(token); false }
413 impl<T: Send> Drop for Packet<T> {
415 assert_eq!(self.channels.load(atomic::SeqCst), 0);
416 let mut guard = self.lock.lock().unwrap();
417 assert!(guard.queue.dequeue().is_none());
418 assert!(guard.canceled.is_none());
423 ////////////////////////////////////////////////////////////////////////////////
424 // Buffer, a simple ring buffer backed by Vec<T>
425 ////////////////////////////////////////////////////////////////////////////////
428 fn enqueue(&mut self, t: T) {
429 let pos = (self.start + self.size) % self.buf.len();
431 let prev = mem::replace(&mut self.buf[pos], Some(t));
432 assert!(prev.is_none());
435 fn dequeue(&mut self) -> T {
436 let start = self.start;
438 self.start = (self.start + 1) % self.buf.len();
439 self.buf[start].take().unwrap()
442 fn size(&self) -> uint { self.size }
443 fn cap(&self) -> uint { self.buf.len() }
446 ////////////////////////////////////////////////////////////////////////////////
447 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
448 ////////////////////////////////////////////////////////////////////////////////
451 fn enqueue(&mut self, node: &mut Node) -> WaitToken {
452 let (wait_token, signal_token) = blocking::tokens();
453 node.token = Some(signal_token);
454 node.next = 0 as *mut Node;
456 if self.tail.is_null() {
457 self.head = node as *mut Node;
458 self.tail = node as *mut Node;
461 (*self.tail).next = node as *mut Node;
462 self.tail = node as *mut Node;
469 fn dequeue(&mut self) -> Option<SignalToken> {
470 if self.head.is_null() {
473 let node = self.head;
474 self.head = unsafe { (*node).next };
475 if self.head.is_null() {
476 self.tail = 0 as *mut Node;
479 (*node).next = 0 as *mut Node;
480 Some((*node).token.take().unwrap())