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 fail 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;
40 use collections::Collection;
43 use rustrt::local::Local;
44 use rustrt::mutex::{NativeMutex, LockGuard};
45 use rustrt::task::{Task, BlockedTask};
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
52 channels: atomics::AtomicUint,
54 /// The state field is protected by this mutex
56 state: Unsafe<State<T>>,
60 disconnected: bool, // Is the channel disconnected yet?
61 queue: Queue, // queue of senders waiting to send data
62 blocker: Blocker, // currently blocked task on this channel
63 buf: Buffer<T>, // storage for buffered messages
64 cap: uint, // capacity of this channel
66 /// A curious flag used to indicate whether a sender failed or succeeded in
67 /// blocking. This is used to transmit information back to the task that it
68 /// must dequeue its message from the buffer because it was not received.
69 /// This is only relevant in the 0-buffer case. This obviously cannot be
70 /// safely constructed, but it's guaranteed to always have a valid pointer
72 canceled: Option<&'static mut bool>,
75 /// Possible flavors of tasks who can be blocked on this channel.
77 BlockedSender(BlockedTask),
78 BlockedReceiver(BlockedTask),
82 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
83 /// this structure is not safe at all
90 task: Option<BlockedTask>,
94 /// A simple ring-buffer
107 /// Atomically blocks the current task, placing it into `slot`, unlocking `lock`
108 /// in the meantime. This re-locks the mutex upon returning.
109 fn wait(slot: &mut Blocker, f: fn(BlockedTask) -> Blocker,
110 lock: &NativeMutex) {
111 let me: Box<Task> = Local::take();
112 me.deschedule(1, |task| {
113 match mem::replace(slot, f(task)) {
117 unsafe { lock.unlock_noguard(); }
120 unsafe { lock.lock_noguard(); }
123 /// Wakes up a task, dropping the lock at the correct time
124 fn wakeup(task: BlockedTask, guard: LockGuard) {
125 // We need to be careful to wake up the waiting task *outside* of the mutex
126 // in case it incurs a context switch.
128 task.wake().map(|t| t.reawaken());
131 impl<T: Send> Packet<T> {
132 pub fn new(cap: uint) -> Packet<T> {
134 channels: atomics::AtomicUint::new(1),
135 lock: unsafe { NativeMutex::new() },
136 state: Unsafe::new(State {
138 blocker: NoneBlocked,
142 head: 0 as *mut Node,
143 tail: 0 as *mut Node,
146 buf: Vec::from_fn(cap + if cap == 0 {1} else {0}, |_| None),
154 // Locks this channel, returning a guard for the state and the mutable state
155 // itself. Care should be taken to ensure that the state does not escape the
158 // Note that we're ok promoting an & reference to an &mut reference because
159 // the lock ensures that we're the only ones in the world with a pointer to
161 fn lock<'a>(&'a self) -> (LockGuard<'a>, &'a mut State<T>) {
163 let guard = self.lock.lock();
164 (guard, &mut *self.state.get())
168 pub fn send(&self, t: T) -> Result<(), T> {
169 let (guard, state) = self.lock();
171 // wait for a slot to become available, and enqueue the data
172 while !state.disconnected && state.buf.size() == state.buf.cap() {
173 state.queue.enqueue(&self.lock);
175 if state.disconnected { return Err(t) }
176 state.buf.enqueue(t);
178 match mem::replace(&mut state.blocker, NoneBlocked) {
179 // if our capacity is 0, then we need to wait for a receiver to be
180 // available to take our data. After waiting, we check again to make
181 // sure the port didn't go away in the meantime. If it did, we need
182 // to hand back our data.
183 NoneBlocked if state.cap == 0 => {
184 let mut canceled = false;
185 assert!(state.canceled.is_none());
186 state.canceled = Some(unsafe { mem::transmute(&mut canceled) });
187 wait(&mut state.blocker, BlockedSender, &self.lock);
188 if canceled {Err(state.buf.dequeue())} else {Ok(())}
191 // success, we buffered some data
192 NoneBlocked => Ok(()),
194 // success, someone's about to receive our buffered data.
195 BlockedReceiver(task) => { wakeup(task, guard); Ok(()) }
197 BlockedSender(..) => fail!("lolwut"),
201 pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
202 let (guard, state) = self.lock();
203 if state.disconnected {
204 Err(super::RecvDisconnected(t))
205 } else if state.buf.size() == state.buf.cap() {
207 } else if state.cap == 0 {
208 // With capacity 0, even though we have buffer space we can't
209 // transfer the data unless there's a receiver waiting.
210 match mem::replace(&mut state.blocker, NoneBlocked) {
211 NoneBlocked => Err(super::Full(t)),
212 BlockedSender(..) => unreachable!(),
213 BlockedReceiver(task) => {
214 state.buf.enqueue(t);
220 // If the buffer has some space and the capacity isn't 0, then we
221 // just enqueue the data for later retrieval.
222 assert!(state.buf.size() < state.buf.cap());
223 state.buf.enqueue(t);
228 // Receives a message from this channel
230 // When reading this, remember that there can only ever be one receiver at
232 pub fn recv(&self) -> Result<T, ()> {
233 let (guard, state) = self.lock();
235 // Wait for the buffer to have something in it. No need for a while loop
236 // because we're the only receiver.
237 let mut waited = false;
238 if !state.disconnected && state.buf.size() == 0 {
239 wait(&mut state.blocker, BlockedReceiver, &self.lock);
242 if state.disconnected && state.buf.size() == 0 { return Err(()) }
244 // Pick up the data, wake up our neighbors, and carry on
245 assert!(state.buf.size() > 0);
246 let ret = state.buf.dequeue();
247 self.wakeup_senders(waited, guard, state);
251 pub fn try_recv(&self) -> Result<T, Failure> {
252 let (guard, state) = self.lock();
255 if state.disconnected { return Err(Disconnected) }
256 if state.buf.size() == 0 { return Err(Empty) }
258 // Be sure to wake up neighbors
259 let ret = Ok(state.buf.dequeue());
260 self.wakeup_senders(false, guard, state);
265 // Wake up pending senders after some data has been received
267 // * `waited` - flag if the receiver blocked to receive some data, or if it
268 // just picked up some data on the way out
269 // * `guard` - the lock guard that is held over this channel's lock
270 fn wakeup_senders(&self, waited: bool,
272 state: &mut State<T>) {
273 let pending_sender1: Option<BlockedTask> = state.queue.dequeue();
275 // If this is a no-buffer channel (cap == 0), then if we didn't wait we
276 // need to ACK the sender. If we waited, then the sender waking us up
277 // was already the ACK.
278 let pending_sender2 = if state.cap == 0 && !waited {
279 match mem::replace(&mut state.blocker, NoneBlocked) {
281 BlockedReceiver(..) => unreachable!(),
282 BlockedSender(task) => {
283 state.canceled.take();
290 mem::drop((state, guard));
292 // only outside of the lock do we wake up the pending tasks
293 pending_sender1.map(|t| t.wake().map(|t| t.reawaken()));
294 pending_sender2.map(|t| t.wake().map(|t| t.reawaken()));
297 // Prepares this shared packet for a channel clone, essentially just bumping
299 pub fn clone_chan(&self) {
300 self.channels.fetch_add(1, atomics::SeqCst);
303 pub fn drop_chan(&self) {
304 // Only flag the channel as disconnected if we're the last channel
305 match self.channels.fetch_sub(1, atomics::SeqCst) {
310 // Not much to do other than wake up a receiver if one's there
311 let (guard, state) = self.lock();
312 if state.disconnected { return }
313 state.disconnected = true;
314 match mem::replace(&mut state.blocker, NoneBlocked) {
316 BlockedSender(..) => unreachable!(),
317 BlockedReceiver(task) => wakeup(task, guard),
321 pub fn drop_port(&self) {
322 let (guard, state) = self.lock();
324 if state.disconnected { return }
325 state.disconnected = true;
327 // If the capacity is 0, then the sender may want its data back after
328 // we're disconnected. Otherwise it's now our responsibility to destroy
329 // the buffered data. As with many other portions of this code, this
330 // needs to be careful to destroy the data *outside* of the lock to
332 let _data = if state.cap != 0 {
333 mem::replace(&mut state.buf.buf, Vec::new())
337 let mut queue = mem::replace(&mut state.queue, Queue {
338 head: 0 as *mut Node,
339 tail: 0 as *mut Node,
342 let waiter = match mem::replace(&mut state.blocker, NoneBlocked) {
344 BlockedSender(task) => {
345 *state.canceled.take_unwrap() = true;
348 BlockedReceiver(..) => unreachable!(),
350 mem::drop((state, guard));
353 match queue.dequeue() {
354 Some(task) => { task.wake().map(|t| t.reawaken()); }
358 waiter.map(|t| t.wake().map(|t| t.reawaken()));
361 ////////////////////////////////////////////////////////////////////////////
362 // select implementation
363 ////////////////////////////////////////////////////////////////////////////
365 // If Ok, the value is whether this port has data, if Err, then the upgraded
366 // port needs to be checked instead of this one.
367 pub fn can_recv(&self) -> bool {
368 let (_g, state) = self.lock();
369 state.disconnected || state.buf.size() > 0
372 // Attempts to start selection on this port. This can either succeed or fail
373 // because there is data waiting.
374 pub fn start_selection(&self, task: BlockedTask) -> Result<(), BlockedTask>{
375 let (_g, state) = self.lock();
376 if state.disconnected || state.buf.size() > 0 {
379 match mem::replace(&mut state.blocker, BlockedReceiver(task)) {
381 BlockedSender(..) => unreachable!(),
382 BlockedReceiver(..) => unreachable!(),
388 // Remove a previous selecting task from this port. This ensures that the
389 // blocked task will no longer be visible to any other threads.
391 // The return value indicates whether there's data on this port.
392 pub fn abort_selection(&self) -> bool {
393 let (_g, state) = self.lock();
394 match mem::replace(&mut state.blocker, NoneBlocked) {
396 BlockedSender(task) => {
397 state.blocker = BlockedSender(task);
400 BlockedReceiver(task) => { task.trash(); false }
406 impl<T: Send> Drop for Packet<T> {
408 assert_eq!(self.channels.load(atomics::SeqCst), 0);
409 let (_g, state) = self.lock();
410 assert!(state.queue.dequeue().is_none());
411 assert!(state.canceled.is_none());
416 ////////////////////////////////////////////////////////////////////////////////
417 // Buffer, a simple ring buffer backed by Vec<T>
418 ////////////////////////////////////////////////////////////////////////////////
421 fn enqueue(&mut self, t: T) {
422 let pos = (self.start + self.size) % self.buf.len();
424 let prev = mem::replace(self.buf.get_mut(pos), Some(t));
425 assert!(prev.is_none());
428 fn dequeue(&mut self) -> T {
429 let start = self.start;
431 self.start = (self.start + 1) % self.buf.len();
432 self.buf.get_mut(start).take_unwrap()
435 fn size(&self) -> uint { self.size }
436 fn cap(&self) -> uint { self.buf.len() }
439 ////////////////////////////////////////////////////////////////////////////////
440 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
441 ////////////////////////////////////////////////////////////////////////////////
444 fn enqueue(&mut self, lock: &NativeMutex) {
445 let task: Box<Task> = Local::take();
446 let mut node = Node {
448 next: 0 as *mut Node,
450 task.deschedule(1, |task| {
451 node.task = Some(task);
452 if self.tail.is_null() {
453 self.head = &mut node as *mut Node;
454 self.tail = &mut node as *mut Node;
457 (*self.tail).next = &mut node as *mut Node;
458 self.tail = &mut node as *mut Node;
461 unsafe { lock.unlock_noguard(); }
464 unsafe { lock.lock_noguard(); }
465 assert!(node.next.is_null());
468 fn dequeue(&mut self) -> Option<BlockedTask> {
469 if self.head.is_null() {
472 let node = self.head;
473 self.head = unsafe { (*node).next };
474 if self.head.is_null() {
475 self.tail = 0 as *mut Node;
478 (*node).next = 0 as *mut Node;
479 Some((*node).task.take_unwrap())