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.
37 use container::Container;
42 use option::{Some, None, Option};
45 use result::{Result, Ok, Err};
47 use rt::task::{Task, BlockedTask};
50 use unstable::mutex::{NativeMutex, LockGuard};
53 pub struct Packet<T> {
54 /// Only field outside of the mutex. Just done for kicks, but mainly because
55 /// the other shared channel already had the code implemented
56 channels: atomics::AtomicUint,
58 /// The state field is protected by this mutex
60 state: Unsafe<State<T>>,
64 disconnected: bool, // Is the channel disconnected yet?
65 queue: Queue, // queue of senders waiting to send data
66 blocker: Blocker, // currently blocked task on this channel
67 buf: Buffer<T>, // storage for buffered messages
68 cap: uint, // capacity of this channel
70 /// A curious flag used to indicate whether a sender failed or succeeded in
71 /// blocking. This is used to transmit information back to the task that it
72 /// must dequeue its message from the buffer because it was not received.
73 /// This is only relevant in the 0-buffer case. This obviously cannot be
74 /// safely constructed, but it's guaranteed to always have a valid pointer
76 canceled: Option<&'static mut bool>,
79 /// Possible flavors of tasks who can be blocked on this channel.
81 BlockedSender(BlockedTask),
82 BlockedReceiver(BlockedTask),
86 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
87 /// this structure is not safe at all
94 task: Option<BlockedTask>,
98 /// A simple ring-buffer
111 /// Atomically blocks the current task, placing it into `slot`, unlocking `lock`
112 /// in the meantime. This re-locks the mutex upon returning.
113 fn wait(slot: &mut Blocker, f: fn(BlockedTask) -> Blocker,
114 lock: &NativeMutex) {
115 let me: Box<Task> = Local::take();
116 me.deschedule(1, |task| {
117 match mem::replace(slot, f(task)) {
121 unsafe { lock.unlock_noguard(); }
124 unsafe { lock.lock_noguard(); }
127 /// Wakes up a task, dropping the lock at the correct time
128 fn wakeup(task: BlockedTask, guard: LockGuard) {
129 // We need to be careful to wake up the waiting task *outside* of the mutex
130 // in case it incurs a context switch.
132 task.wake().map(|t| t.reawaken());
135 impl<T: Send> Packet<T> {
136 pub fn new(cap: uint) -> Packet<T> {
138 channels: atomics::AtomicUint::new(1),
139 lock: unsafe { NativeMutex::new() },
140 state: Unsafe::new(State {
142 blocker: NoneBlocked,
146 head: 0 as *mut Node,
147 tail: 0 as *mut Node,
150 buf: Vec::from_fn(cap + if cap == 0 {1} else {0}, |_| None),
158 // Locks this channel, returning a guard for the state and the mutable state
159 // itself. Care should be taken to ensure that the state does not escape the
162 // Note that we're ok promoting an & reference to an &mut reference because
163 // the lock ensures that we're the only ones in the world with a pointer to
165 fn lock<'a>(&'a self) -> (LockGuard<'a>, &'a mut State<T>) {
167 let guard = self.lock.lock();
168 (guard, &mut *self.state.get())
172 pub fn send(&self, t: T) -> Result<(), T> {
173 let (guard, state) = self.lock();
175 // wait for a slot to become available, and enqueue the data
176 while !state.disconnected && state.buf.size() == state.buf.cap() {
177 state.queue.enqueue(&self.lock);
179 if state.disconnected { return Err(t) }
180 state.buf.enqueue(t);
182 match mem::replace(&mut state.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 state.cap == 0 => {
188 let mut canceled = false;
189 assert!(state.canceled.is_none());
190 state.canceled = Some(unsafe { cast::transmute(&mut canceled) });
191 wait(&mut state.blocker, BlockedSender, &self.lock);
192 if canceled {Err(state.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(task) => { wakeup(task, guard); Ok(()) }
201 BlockedSender(..) => fail!("lolwut"),
205 pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
206 let (guard, state) = self.lock();
207 if state.disconnected {
208 Err(super::RecvDisconnected(t))
209 } else if state.buf.size() == state.buf.cap() {
211 } else if state.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 state.blocker, NoneBlocked) {
215 NoneBlocked => Err(super::Full(t)),
216 BlockedSender(..) => unreachable!(),
217 BlockedReceiver(task) => {
218 state.buf.enqueue(t);
224 // If the buffer has some space and the capacity isn't 0, then we
225 // just enqueue the data for later retrieval.
226 assert!(state.buf.size() < state.buf.cap());
227 state.buf.enqueue(t);
232 // Receives a message from this channel
234 // When reading this, remember that there can only ever be one receiver at
236 pub fn recv(&self) -> Result<T, ()> {
237 let (guard, state) = self.lock();
239 // Wait for the buffer to have something in it. No need for a while loop
240 // because we're the only receiver.
241 let mut waited = false;
242 if !state.disconnected && state.buf.size() == 0 {
243 wait(&mut state.blocker, BlockedReceiver, &self.lock);
246 if state.disconnected && state.buf.size() == 0 { return Err(()) }
248 // Pick up the data, wake up our neighbors, and carry on
249 assert!(state.buf.size() > 0);
250 let ret = state.buf.dequeue();
251 self.wakeup_senders(waited, guard, state);
255 pub fn try_recv(&self) -> Result<T, Failure> {
256 let (guard, state) = self.lock();
259 if state.disconnected { return Err(Disconnected) }
260 if state.buf.size() == 0 { return Err(Empty) }
262 // Be sure to wake up neighbors
263 let ret = Ok(state.buf.dequeue());
264 self.wakeup_senders(false, guard, state);
269 // Wake up pending senders after some data has been received
271 // * `waited` - flag if the receiver blocked to receive some data, or if it
272 // just picked up some data on the way out
273 // * `guard` - the lock guard that is held over this channel's lock
274 fn wakeup_senders(&self, waited: bool,
276 state: &mut State<T>) {
277 let pending_sender1: Option<BlockedTask> = state.queue.dequeue();
279 // If this is a no-buffer channel (cap == 0), then if we didn't wait we
280 // need to ACK the sender. If we waited, then the sender waking us up
281 // was already the ACK.
282 let pending_sender2 = if state.cap == 0 && !waited {
283 match mem::replace(&mut state.blocker, NoneBlocked) {
285 BlockedReceiver(..) => unreachable!(),
286 BlockedSender(task) => {
287 state.canceled.take();
294 mem::drop((state, guard));
296 // only outside of the lock do we wake up the pending tasks
297 pending_sender1.map(|t| t.wake().map(|t| t.reawaken()));
298 pending_sender2.map(|t| t.wake().map(|t| t.reawaken()));
301 // Prepares this shared packet for a channel clone, essentially just bumping
303 pub fn clone_chan(&self) {
304 self.channels.fetch_add(1, atomics::SeqCst);
307 pub fn drop_chan(&self) {
308 // Only flag the channel as disconnected if we're the last channel
309 match self.channels.fetch_sub(1, atomics::SeqCst) {
314 // Not much to do other than wake up a receiver if one's there
315 let (guard, state) = self.lock();
316 if state.disconnected { return }
317 state.disconnected = true;
318 match mem::replace(&mut state.blocker, NoneBlocked) {
320 BlockedSender(..) => unreachable!(),
321 BlockedReceiver(task) => wakeup(task, guard),
325 pub fn drop_port(&self) {
326 let (guard, state) = self.lock();
328 if state.disconnected { return }
329 state.disconnected = true;
331 // If the capacity is 0, then the sender may want its data back after
332 // we're disconnected. Otherwise it's now our responsibility to destroy
333 // the buffered data. As with many other portions of this code, this
334 // needs to be careful to destroy the data *outside* of the lock to
336 let _data = if state.cap != 0 {
337 mem::replace(&mut state.buf.buf, Vec::new())
341 let mut queue = mem::replace(&mut state.queue, Queue {
342 head: 0 as *mut Node,
343 tail: 0 as *mut Node,
346 let waiter = match mem::replace(&mut state.blocker, NoneBlocked) {
348 BlockedSender(task) => {
349 *state.canceled.take_unwrap() = true;
352 BlockedReceiver(..) => unreachable!(),
354 mem::drop((state, guard));
357 match queue.dequeue() {
358 Some(task) => { task.wake().map(|t| t.reawaken()); }
362 waiter.map(|t| t.wake().map(|t| t.reawaken()));
365 ////////////////////////////////////////////////////////////////////////////
366 // select implementation
367 ////////////////////////////////////////////////////////////////////////////
369 // If Ok, the value is whether this port has data, if Err, then the upgraded
370 // port needs to be checked instead of this one.
371 pub fn can_recv(&self) -> bool {
372 let (_g, state) = self.lock();
373 state.disconnected || state.buf.size() > 0
376 // Attempts to start selection on this port. This can either succeed or fail
377 // because there is data waiting.
378 pub fn start_selection(&self, task: BlockedTask) -> Result<(), BlockedTask>{
379 let (_g, state) = self.lock();
380 if state.disconnected || state.buf.size() > 0 {
383 match mem::replace(&mut state.blocker, BlockedReceiver(task)) {
385 BlockedSender(..) => unreachable!(),
386 BlockedReceiver(..) => unreachable!(),
392 // Remove a previous selecting task from this port. This ensures that the
393 // blocked task will no longer be visible to any other threads.
395 // The return value indicates whether there's data on this port.
396 pub fn abort_selection(&self) -> bool {
397 let (_g, state) = self.lock();
398 match mem::replace(&mut state.blocker, NoneBlocked) {
400 BlockedSender(task) => {
401 state.blocker = BlockedSender(task);
404 BlockedReceiver(task) => { task.trash(); false }
410 impl<T: Send> Drop for Packet<T> {
412 assert_eq!(self.channels.load(atomics::SeqCst), 0);
413 let (_g, state) = self.lock();
414 assert!(state.queue.dequeue().is_none());
415 assert!(state.canceled.is_none());
420 ////////////////////////////////////////////////////////////////////////////////
421 // Buffer, a simple ring buffer backed by Vec<T>
422 ////////////////////////////////////////////////////////////////////////////////
425 fn enqueue(&mut self, t: T) {
426 let pos = (self.start + self.size) % self.buf.len();
428 let prev = mem::replace(self.buf.get_mut(pos), Some(t));
429 assert!(prev.is_none());
432 fn dequeue(&mut self) -> T {
433 let start = self.start;
435 self.start = (self.start + 1) % self.buf.len();
436 self.buf.get_mut(start).take_unwrap()
439 fn size(&self) -> uint { self.size }
440 fn cap(&self) -> uint { self.buf.len() }
443 ////////////////////////////////////////////////////////////////////////////////
444 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
445 ////////////////////////////////////////////////////////////////////////////////
448 fn enqueue(&mut self, lock: &NativeMutex) {
449 let task: Box<Task> = Local::take();
450 let mut node = Node {
452 next: 0 as *mut Node,
454 task.deschedule(1, |task| {
455 node.task = Some(task);
456 if self.tail.is_null() {
457 self.head = &mut node as *mut Node;
458 self.tail = &mut node as *mut Node;
461 (*self.tail).next = &mut node as *mut Node;
462 self.tail = &mut node as *mut Node;
465 unsafe { lock.unlock_noguard(); }
468 unsafe { lock.lock_noguard(); }
469 assert!(node.next.is_null());
472 fn dequeue(&mut self) -> Option<BlockedTask> {
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 = 0 as *mut Node;
482 (*node).next = 0 as *mut Node;
483 Some((*node).task.take_unwrap())