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 use alloc::boxed::Box;
41 use core::cell::UnsafeCell;
42 use rustrt::local::Local;
43 use rustrt::mutex::{NativeMutex, LockGuard};
44 use rustrt::task::{Task, BlockedTask};
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 /// The state field is protected by this mutex
55 state: UnsafeCell<State<T>>,
59 disconnected: bool, // Is the channel disconnected yet?
60 queue: Queue, // queue of senders waiting to send data
61 blocker: Blocker, // currently blocked task on this channel
62 buf: Buffer<T>, // storage for buffered messages
63 cap: uint, // capacity of this channel
65 /// A curious flag used to indicate whether a sender failed or succeeded in
66 /// blocking. This is used to transmit information back to the task that it
67 /// must dequeue its message from the buffer because it was not received.
68 /// This is only relevant in the 0-buffer case. This obviously cannot be
69 /// safely constructed, but it's guaranteed to always have a valid pointer
71 canceled: Option<&'static mut bool>,
74 /// Possible flavors of tasks who can be blocked on this channel.
76 BlockedSender(BlockedTask),
77 BlockedReceiver(BlockedTask),
81 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
82 /// this structure is not safe at all
89 task: Option<BlockedTask>,
93 /// A simple ring-buffer
106 /// Atomically blocks the current task, placing it into `slot`, unlocking `lock`
107 /// in the meantime. This re-locks the mutex upon returning.
108 fn wait(slot: &mut Blocker, f: fn(BlockedTask) -> Blocker,
109 lock: &NativeMutex) {
110 let me: Box<Task> = Local::take();
111 me.deschedule(1, |task| {
112 match mem::replace(slot, f(task)) {
116 unsafe { lock.unlock_noguard(); }
119 unsafe { lock.lock_noguard(); }
122 /// Wakes up a task, dropping the lock at the correct time
123 fn wakeup(task: BlockedTask, guard: LockGuard) {
124 // We need to be careful to wake up the waiting task *outside* of the mutex
125 // in case it incurs a context switch.
127 task.wake().map(|t| t.reawaken());
130 impl<T: Send> Packet<T> {
131 pub fn new(cap: uint) -> Packet<T> {
133 channels: atomic::AtomicUint::new(1),
134 lock: unsafe { NativeMutex::new() },
135 state: UnsafeCell::new(State {
137 blocker: NoneBlocked,
141 head: 0 as *mut Node,
142 tail: 0 as *mut Node,
145 buf: Vec::from_fn(cap + if cap == 0 {1} else {0}, |_| None),
153 // Locks this channel, returning a guard for the state and the mutable state
154 // itself. Care should be taken to ensure that the state does not escape the
157 // Note that we're ok promoting an & reference to an &mut reference because
158 // the lock ensures that we're the only ones in the world with a pointer to
160 fn lock<'a>(&'a self) -> (LockGuard<'a>, &'a mut State<T>) {
162 let guard = self.lock.lock();
163 (guard, &mut *self.state.get())
167 pub fn send(&self, t: T) -> Result<(), T> {
168 let (guard, state) = self.lock();
170 // wait for a slot to become available, and enqueue the data
171 while !state.disconnected && state.buf.size() == state.buf.cap() {
172 state.queue.enqueue(&self.lock);
174 if state.disconnected { return Err(t) }
175 state.buf.enqueue(t);
177 match mem::replace(&mut state.blocker, NoneBlocked) {
178 // if our capacity is 0, then we need to wait for a receiver to be
179 // available to take our data. After waiting, we check again to make
180 // sure the port didn't go away in the meantime. If it did, we need
181 // to hand back our data.
182 NoneBlocked if state.cap == 0 => {
183 let mut canceled = false;
184 assert!(state.canceled.is_none());
185 state.canceled = Some(unsafe { mem::transmute(&mut canceled) });
186 wait(&mut state.blocker, BlockedSender, &self.lock);
187 if canceled {Err(state.buf.dequeue())} else {Ok(())}
190 // success, we buffered some data
191 NoneBlocked => Ok(()),
193 // success, someone's about to receive our buffered data.
194 BlockedReceiver(task) => { wakeup(task, guard); Ok(()) }
196 BlockedSender(..) => panic!("lolwut"),
200 pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
201 let (guard, state) = self.lock();
202 if state.disconnected {
203 Err(super::RecvDisconnected(t))
204 } else if state.buf.size() == state.buf.cap() {
206 } else if state.cap == 0 {
207 // With capacity 0, even though we have buffer space we can't
208 // transfer the data unless there's a receiver waiting.
209 match mem::replace(&mut state.blocker, NoneBlocked) {
210 NoneBlocked => Err(super::Full(t)),
211 BlockedSender(..) => unreachable!(),
212 BlockedReceiver(task) => {
213 state.buf.enqueue(t);
219 // If the buffer has some space and the capacity isn't 0, then we
220 // just enqueue the data for later retrieval, ensuring to wake up
221 // any blocked receiver if there is one.
222 assert!(state.buf.size() < state.buf.cap());
223 state.buf.enqueue(t);
224 match mem::replace(&mut state.blocker, NoneBlocked) {
225 BlockedReceiver(task) => wakeup(task, guard),
227 BlockedSender(..) => unreachable!(),
233 // Receives a message from this channel
235 // When reading this, remember that there can only ever be one receiver at
237 pub fn recv(&self) -> Result<T, ()> {
238 let (guard, state) = self.lock();
240 // Wait for the buffer to have something in it. No need for a while loop
241 // because we're the only receiver.
242 let mut waited = false;
243 if !state.disconnected && state.buf.size() == 0 {
244 wait(&mut state.blocker, BlockedReceiver, &self.lock);
247 if state.disconnected && state.buf.size() == 0 { return Err(()) }
249 // Pick up the data, wake up our neighbors, and carry on
250 assert!(state.buf.size() > 0);
251 let ret = state.buf.dequeue();
252 self.wakeup_senders(waited, guard, state);
256 pub fn try_recv(&self) -> Result<T, Failure> {
257 let (guard, state) = self.lock();
260 if state.disconnected { return Err(Disconnected) }
261 if state.buf.size() == 0 { return Err(Empty) }
263 // Be sure to wake up neighbors
264 let ret = Ok(state.buf.dequeue());
265 self.wakeup_senders(false, guard, state);
270 // Wake up pending senders after some data has been received
272 // * `waited` - flag if the receiver blocked to receive some data, or if it
273 // just picked up some data on the way out
274 // * `guard` - the lock guard that is held over this channel's lock
275 fn wakeup_senders(&self, waited: bool,
277 state: &mut State<T>) {
278 let pending_sender1: Option<BlockedTask> = state.queue.dequeue();
280 // If this is a no-buffer channel (cap == 0), then if we didn't wait we
281 // need to ACK the sender. If we waited, then the sender waking us up
282 // was already the ACK.
283 let pending_sender2 = if state.cap == 0 && !waited {
284 match mem::replace(&mut state.blocker, NoneBlocked) {
286 BlockedReceiver(..) => unreachable!(),
287 BlockedSender(task) => {
288 state.canceled.take();
295 mem::drop((state, guard));
297 // only outside of the lock do we wake up the pending tasks
298 pending_sender1.map(|t| t.wake().map(|t| t.reawaken()));
299 pending_sender2.map(|t| t.wake().map(|t| t.reawaken()));
302 // Prepares this shared packet for a channel clone, essentially just bumping
304 pub fn clone_chan(&self) {
305 self.channels.fetch_add(1, atomic::SeqCst);
308 pub fn drop_chan(&self) {
309 // Only flag the channel as disconnected if we're the last channel
310 match self.channels.fetch_sub(1, atomic::SeqCst) {
315 // Not much to do other than wake up a receiver if one's there
316 let (guard, state) = self.lock();
317 if state.disconnected { return }
318 state.disconnected = true;
319 match mem::replace(&mut state.blocker, NoneBlocked) {
321 BlockedSender(..) => unreachable!(),
322 BlockedReceiver(task) => wakeup(task, guard),
326 pub fn drop_port(&self) {
327 let (guard, state) = self.lock();
329 if state.disconnected { return }
330 state.disconnected = true;
332 // If the capacity is 0, then the sender may want its data back after
333 // we're disconnected. Otherwise it's now our responsibility to destroy
334 // the buffered data. As with many other portions of this code, this
335 // needs to be careful to destroy the data *outside* of the lock to
337 let _data = if state.cap != 0 {
338 mem::replace(&mut state.buf.buf, Vec::new())
342 let mut queue = mem::replace(&mut state.queue, Queue {
343 head: 0 as *mut Node,
344 tail: 0 as *mut Node,
347 let waiter = match mem::replace(&mut state.blocker, NoneBlocked) {
349 BlockedSender(task) => {
350 *state.canceled.take().unwrap() = true;
353 BlockedReceiver(..) => unreachable!(),
355 mem::drop((state, guard));
358 match queue.dequeue() {
359 Some(task) => { task.wake().map(|t| t.reawaken()); }
363 waiter.map(|t| t.wake().map(|t| t.reawaken()));
366 ////////////////////////////////////////////////////////////////////////////
367 // select implementation
368 ////////////////////////////////////////////////////////////////////////////
370 // If Ok, the value is whether this port has data, if Err, then the upgraded
371 // port needs to be checked instead of this one.
372 pub fn can_recv(&self) -> bool {
373 let (_g, state) = self.lock();
374 state.disconnected || state.buf.size() > 0
377 // Attempts to start selection on this port. This can either succeed or fail
378 // because there is data waiting.
379 pub fn start_selection(&self, task: BlockedTask) -> Result<(), BlockedTask>{
380 let (_g, state) = self.lock();
381 if state.disconnected || state.buf.size() > 0 {
384 match mem::replace(&mut state.blocker, BlockedReceiver(task)) {
386 BlockedSender(..) => unreachable!(),
387 BlockedReceiver(..) => unreachable!(),
393 // Remove a previous selecting task from this port. This ensures that the
394 // blocked task will no longer be visible to any other threads.
396 // The return value indicates whether there's data on this port.
397 pub fn abort_selection(&self) -> bool {
398 let (_g, state) = self.lock();
399 match mem::replace(&mut state.blocker, NoneBlocked) {
401 BlockedSender(task) => {
402 state.blocker = BlockedSender(task);
405 BlockedReceiver(task) => { task.trash(); false }
411 impl<T: Send> Drop for Packet<T> {
413 assert_eq!(self.channels.load(atomic::SeqCst), 0);
414 let (_g, state) = self.lock();
415 assert!(state.queue.dequeue().is_none());
416 assert!(state.canceled.is_none());
421 ////////////////////////////////////////////////////////////////////////////////
422 // Buffer, a simple ring buffer backed by Vec<T>
423 ////////////////////////////////////////////////////////////////////////////////
426 fn enqueue(&mut self, t: T) {
427 let pos = (self.start + self.size) % self.buf.len();
429 let prev = mem::replace(self.buf.get_mut(pos), Some(t));
430 assert!(prev.is_none());
433 fn dequeue(&mut self) -> T {
434 let start = self.start;
436 self.start = (self.start + 1) % self.buf.len();
437 self.buf.get_mut(start).take().unwrap()
440 fn size(&self) -> uint { self.size }
441 fn cap(&self) -> uint { self.buf.len() }
444 ////////////////////////////////////////////////////////////////////////////////
445 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
446 ////////////////////////////////////////////////////////////////////////////////
449 fn enqueue(&mut self, lock: &NativeMutex) {
450 let task: Box<Task> = Local::take();
451 let mut node = Node {
453 next: 0 as *mut Node,
455 task.deschedule(1, |task| {
456 node.task = Some(task);
457 if self.tail.is_null() {
458 self.head = &mut node as *mut Node;
459 self.tail = &mut node as *mut Node;
462 (*self.tail).next = &mut node as *mut Node;
463 self.tail = &mut node as *mut Node;
466 unsafe { lock.unlock_noguard(); }
469 unsafe { lock.lock_noguard(); }
470 assert!(node.next.is_null());
473 fn dequeue(&mut self) -> Option<BlockedTask> {
474 if self.head.is_null() {
477 let node = self.head;
478 self.head = unsafe { (*node).next };
479 if self.head.is_null() {
480 self.tail = 0 as *mut Node;
483 (*node).next = 0 as *mut Node;
484 Some((*node).task.take().unwrap())