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};
44 use result::{Result, Ok, Err};
46 use rt::task::{Task, BlockedTask};
49 use unstable::mutex::{NativeMutex, LockGuard};
52 pub struct Packet<T> {
53 /// Only field outside of the mutex. Just done for kicks, but mainly because
54 /// the other shared channel already had the code implemented
55 channels: atomics::AtomicUint,
57 /// The state field is protected by this mutex
59 state: Unsafe<State<T>>,
63 disconnected: bool, // Is the channel disconnected yet?
64 queue: Queue, // queue of senders waiting to send data
65 blocker: Blocker, // currently blocked task on this channel
66 buf: Buffer<T>, // storage for buffered messages
67 cap: uint, // capacity of this channel
69 /// A curious flag used to indicate whether a sender failed or succeeded in
70 /// blocking. This is used to transmit information back to the task that it
71 /// must dequeue its message from the buffer because it was not received.
72 /// This is only relevant in the 0-buffer case. This obviously cannot be
73 /// safely constructed, but it's guaranteed to always have a valid pointer
75 canceled: Option<&'static mut bool>,
78 /// Possible flavors of tasks who can be blocked on this channel.
80 BlockedSender(BlockedTask),
81 BlockedReceiver(BlockedTask),
85 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
86 /// this structure is not safe at all
93 task: Option<BlockedTask>,
97 /// A simple ring-buffer
110 /// Atomically blocks the current task, placing it into `slot`, unlocking `lock`
111 /// in the meantime. This re-locks the mutex upon returning.
112 fn wait(slot: &mut Blocker, f: fn(BlockedTask) -> Blocker,
113 lock: &NativeMutex) {
114 let me: ~Task = Local::take();
115 me.deschedule(1, |task| {
116 match mem::replace(slot, f(task)) {
120 unsafe { lock.unlock_noguard(); }
123 unsafe { lock.lock_noguard(); }
126 /// Wakes up a task, dropping the lock at the correct time
127 fn wakeup(task: BlockedTask, guard: LockGuard) {
128 // We need to be careful to wake up the waiting task *outside* of the mutex
129 // in case it incurs a context switch.
131 task.wake().map(|t| t.reawaken());
134 impl<T: Send> Packet<T> {
135 pub fn new(cap: uint) -> Packet<T> {
137 channels: atomics::AtomicUint::new(1),
138 lock: unsafe { NativeMutex::new() },
139 state: Unsafe::new(State {
141 blocker: NoneBlocked,
145 head: 0 as *mut Node,
146 tail: 0 as *mut Node,
149 buf: Vec::from_fn(cap + if cap == 0 {1} else {0}, |_| None),
157 // Locks this channel, returning a guard for the state and the mutable state
158 // itself. Care should be taken to ensure that the state does not escape the
161 // Note that we're ok promoting an & reference to an &mut reference because
162 // the lock ensures that we're the only ones in the world with a pointer to
164 fn lock<'a>(&'a self) -> (LockGuard<'a>, &'a mut State<T>) {
166 let guard = self.lock.lock();
167 (guard, &mut *self.state.get())
171 pub fn send(&self, t: T) -> Result<(), T> {
172 let (guard, state) = self.lock();
174 // wait for a slot to become available, and enqueue the data
175 while !state.disconnected && state.buf.size() == state.buf.cap() {
176 state.queue.enqueue(&self.lock);
178 if state.disconnected { return Err(t) }
179 state.buf.enqueue(t);
181 match mem::replace(&mut state.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 state.cap == 0 => {
187 let mut canceled = false;
188 assert!(state.canceled.is_none());
189 state.canceled = Some(unsafe { cast::transmute(&mut canceled) });
190 wait(&mut state.blocker, BlockedSender, &self.lock);
191 if canceled {Err(state.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(task) => { wakeup(task, guard); Ok(()) }
200 BlockedSender(..) => fail!("lolwut"),
204 pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
205 let (guard, state) = self.lock();
206 if state.disconnected {
207 Err(super::RecvDisconnected(t))
208 } else if state.buf.size() == state.buf.cap() {
210 } else if state.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 state.blocker, NoneBlocked) {
214 NoneBlocked => Err(super::Full(t)),
215 BlockedSender(..) => unreachable!(),
216 BlockedReceiver(task) => {
217 state.buf.enqueue(t);
223 // If the buffer has some space and the capacity isn't 0, then we
224 // just enqueue the data for later retrieval.
225 assert!(state.buf.size() < state.buf.cap());
226 state.buf.enqueue(t);
231 // Receives a message from this channel
233 // When reading this, remember that there can only ever be one receiver at
235 pub fn recv(&self) -> Result<T, ()> {
236 let (guard, state) = self.lock();
238 // Wait for the buffer to have something in it. No need for a while loop
239 // because we're the only receiver.
240 let mut waited = false;
241 if !state.disconnected && state.buf.size() == 0 {
242 wait(&mut state.blocker, BlockedReceiver, &self.lock);
245 if state.disconnected && state.buf.size() == 0 { return Err(()) }
247 // Pick up the data, wake up our neighbors, and carry on
248 assert!(state.buf.size() > 0);
249 let ret = state.buf.dequeue();
250 self.wakeup_senders(waited, guard, state);
254 pub fn try_recv(&self) -> Result<T, Failure> {
255 let (guard, state) = self.lock();
258 if state.disconnected { return Err(Disconnected) }
259 if state.buf.size() == 0 { return Err(Empty) }
261 // Be sure to wake up neighbors
262 let ret = Ok(state.buf.dequeue());
263 self.wakeup_senders(false, guard, state);
268 // Wake up pending senders after some data has been received
270 // * `waited` - flag if the receiver blocked to receive some data, or if it
271 // just picked up some data on the way out
272 // * `guard` - the lock guard that is held over this channel's lock
273 fn wakeup_senders(&self, waited: bool,
275 state: &mut State<T>) {
276 let pending_sender1: Option<BlockedTask> = state.queue.dequeue();
278 // If this is a no-buffer channel (cap == 0), then if we didn't wait we
279 // need to ACK the sender. If we waited, then the sender waking us up
280 // was already the ACK.
281 let pending_sender2 = if state.cap == 0 && !waited {
282 match mem::replace(&mut state.blocker, NoneBlocked) {
284 BlockedReceiver(..) => unreachable!(),
285 BlockedSender(task) => {
286 state.canceled.take();
293 mem::drop((state, guard));
295 // only outside of the lock do we wake up the pending tasks
296 pending_sender1.map(|t| t.wake().map(|t| t.reawaken()));
297 pending_sender2.map(|t| t.wake().map(|t| t.reawaken()));
300 // Prepares this shared packet for a channel clone, essentially just bumping
302 pub fn clone_chan(&self) {
303 self.channels.fetch_add(1, atomics::SeqCst);
306 pub fn drop_chan(&self) {
307 // Only flag the channel as disconnected if we're the last channel
308 match self.channels.fetch_sub(1, atomics::SeqCst) {
313 // Not much to do other than wake up a receiver if one's there
314 let (guard, state) = self.lock();
315 if state.disconnected { return }
316 state.disconnected = true;
317 match mem::replace(&mut state.blocker, NoneBlocked) {
319 BlockedSender(..) => unreachable!(),
320 BlockedReceiver(task) => wakeup(task, guard),
324 pub fn drop_port(&self) {
325 let (guard, state) = self.lock();
327 if state.disconnected { return }
328 state.disconnected = true;
330 // If the capacity is 0, then the sender may want its data back after
331 // we're disconnected. Otherwise it's now our responsibility to destroy
332 // the buffered data. As with many other portions of this code, this
333 // needs to be careful to destroy the data *outside* of the lock to
335 let _data = if state.cap != 0 {
336 mem::replace(&mut state.buf.buf, Vec::new())
340 let mut queue = mem::replace(&mut state.queue, Queue {
341 head: 0 as *mut Node,
342 tail: 0 as *mut Node,
345 let waiter = match mem::replace(&mut state.blocker, NoneBlocked) {
347 BlockedSender(task) => {
348 *state.canceled.take_unwrap() = true;
351 BlockedReceiver(..) => unreachable!(),
353 mem::drop((state, guard));
356 match queue.dequeue() {
357 Some(task) => { task.wake().map(|t| t.reawaken()); }
361 waiter.map(|t| t.wake().map(|t| t.reawaken()));
364 ////////////////////////////////////////////////////////////////////////////
365 // select implementation
366 ////////////////////////////////////////////////////////////////////////////
368 // If Ok, the value is whether this port has data, if Err, then the upgraded
369 // port needs to be checked instead of this one.
370 pub fn can_recv(&self) -> bool {
371 let (_g, state) = self.lock();
372 state.disconnected || state.buf.size() > 0
375 // Attempts to start selection on this port. This can either succeed or fail
376 // because there is data waiting.
377 pub fn start_selection(&self, task: BlockedTask) -> Result<(), BlockedTask>{
378 let (_g, state) = self.lock();
379 if state.disconnected || state.buf.size() > 0 {
382 match mem::replace(&mut state.blocker, BlockedReceiver(task)) {
384 BlockedSender(..) => unreachable!(),
385 BlockedReceiver(..) => unreachable!(),
391 // Remove a previous selecting task from this port. This ensures that the
392 // blocked task will no longer be visible to any other threads.
394 // The return value indicates whether there's data on this port.
395 pub fn abort_selection(&self) -> bool {
396 let (_g, state) = self.lock();
397 match mem::replace(&mut state.blocker, NoneBlocked) {
399 BlockedSender(task) => {
400 state.blocker = BlockedSender(task);
403 BlockedReceiver(task) => { task.trash(); false }
409 impl<T: Send> Drop for Packet<T> {
411 assert_eq!(self.channels.load(atomics::SeqCst), 0);
412 let (_g, state) = self.lock();
413 assert!(state.queue.dequeue().is_none());
414 assert!(state.canceled.is_none());
419 ////////////////////////////////////////////////////////////////////////////////
420 // Buffer, a simple ring buffer backed by Vec<T>
421 ////////////////////////////////////////////////////////////////////////////////
424 fn enqueue(&mut self, t: T) {
425 let pos = (self.start + self.size) % self.buf.len();
427 let prev = mem::replace(self.buf.get_mut(pos), Some(t));
428 assert!(prev.is_none());
431 fn dequeue(&mut self) -> T {
432 let start = self.start;
434 self.start = (self.start + 1) % self.buf.len();
435 self.buf.get_mut(start).take_unwrap()
438 fn size(&self) -> uint { self.size }
439 fn cap(&self) -> uint { self.buf.len() }
442 ////////////////////////////////////////////////////////////////////////////////
443 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
444 ////////////////////////////////////////////////////////////////////////////////
447 fn enqueue(&mut self, lock: &NativeMutex) {
448 let task: ~Task = Local::take();
449 let mut node = Node {
451 next: 0 as *mut Node,
453 task.deschedule(1, |task| {
454 node.task = Some(task);
455 if self.tail.is_null() {
456 self.head = &mut node as *mut Node;
457 self.tail = &mut node as *mut Node;
460 (*self.tail).next = &mut node as *mut Node;
461 self.tail = &mut node as *mut Node;
464 unsafe { lock.unlock_noguard(); }
467 unsafe { lock.lock_noguard(); }
468 assert!(node.next.is_null());
471 fn dequeue(&mut self) -> Option<BlockedTask> {
472 if self.head.is_null() {
475 let node = self.head;
476 self.head = unsafe { (*node).next };
477 if self.head.is_null() {
478 self.tail = 0 as *mut Node;
481 (*node).next = 0 as *mut Node;
482 Some((*node).task.take_unwrap())