]> git.lizzy.rs Git - rust.git/blob - src/libstd/comm/sync.rs
Ignore tests broken by failing on ICE
[rust.git] / src / libstd / comm / sync.rs
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.
4 //
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.
10
11 /// Synchronous channels/ports
12 ///
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.
16 ///
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.
20 ///
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.
24 ///
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.
28 ///
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.
35
36 use cast;
37 use container::Container;
38 use iter::Iterator;
39 use kinds::Send;
40 use mem;
41 use ops::Drop;
42 use option::{Some, None, Option};
43 use ptr::RawPtr;
44 use result::{Result, Ok, Err};
45 use rt::local::Local;
46 use rt::task::{Task, BlockedTask};
47 use sync::atomics;
48 use ty::Unsafe;
49 use unstable::mutex::{NativeMutex, LockGuard};
50 use vec::Vec;
51
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,
56
57     /// The state field is protected by this mutex
58     lock: NativeMutex,
59     state: Unsafe<State<T>>,
60 }
61
62 struct 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
68
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
74     /// value.
75     canceled: Option<&'static mut bool>,
76 }
77
78 /// Possible flavors of tasks who can be blocked on this channel.
79 enum Blocker {
80     BlockedSender(BlockedTask),
81     BlockedReceiver(BlockedTask),
82     NoneBlocked
83 }
84
85 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
86 /// this structure is not safe at all
87 struct Queue {
88     head: *mut Node,
89     tail: *mut Node,
90 }
91
92 struct Node {
93     task: Option<BlockedTask>,
94     next: *mut Node,
95 }
96
97 /// A simple ring-buffer
98 struct Buffer<T> {
99     buf: Vec<Option<T>>,
100     start: uint,
101     size: uint,
102 }
103
104 #[deriving(Show)]
105 pub enum Failure {
106     Empty,
107     Disconnected,
108 }
109
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)) {
117             NoneBlocked => {}
118             _ => unreachable!(),
119         }
120         unsafe { lock.unlock_noguard(); }
121         Ok(())
122     });
123     unsafe { lock.lock_noguard(); }
124 }
125
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.
130     mem::drop(guard);
131     task.wake().map(|t| t.reawaken());
132 }
133
134 impl<T: Send> Packet<T> {
135     pub fn new(cap: uint) -> Packet<T> {
136         Packet {
137             channels: atomics::AtomicUint::new(1),
138             lock: unsafe { NativeMutex::new() },
139             state: Unsafe::new(State {
140                 disconnected: false,
141                 blocker: NoneBlocked,
142                 cap: cap,
143                 canceled: None,
144                 queue: Queue {
145                     head: 0 as *mut Node,
146                     tail: 0 as *mut Node,
147                 },
148                 buf: Buffer {
149                     buf: Vec::from_fn(cap + if cap == 0 {1} else {0}, |_| None),
150                     start: 0,
151                     size: 0,
152                 },
153             }),
154         }
155     }
156
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
159     // guard!
160     //
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
163     // the state.
164     fn lock<'a>(&'a self) -> (LockGuard<'a>, &'a mut State<T>) {
165         unsafe {
166             let guard = self.lock.lock();
167             (guard, &mut *self.state.get())
168         }
169     }
170
171     pub fn send(&self, t: T) -> Result<(), T> {
172         let (guard, state) = self.lock();
173
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);
177         }
178         if state.disconnected { return Err(t) }
179         state.buf.enqueue(t);
180
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(())}
192             }
193
194             // success, we buffered some data
195             NoneBlocked => Ok(()),
196
197             // success, someone's about to receive our buffered data.
198             BlockedReceiver(task) => { wakeup(task, guard); Ok(()) }
199
200             BlockedSender(..) => fail!("lolwut"),
201         }
202     }
203
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() {
209             Err(super::Full(t))
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);
218                     wakeup(task, guard);
219                     Ok(())
220                 }
221             }
222         } else {
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);
227             Ok(())
228         }
229     }
230
231     // Receives a message from this channel
232     //
233     // When reading this, remember that there can only ever be one receiver at
234     // time.
235     pub fn recv(&self) -> Result<T, ()> {
236         let (guard, state) = self.lock();
237
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);
243             waited = true;
244         }
245         if state.disconnected && state.buf.size() == 0 { return Err(()) }
246
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);
251         return Ok(ret);
252     }
253
254     pub fn try_recv(&self) -> Result<T, Failure> {
255         let (guard, state) = self.lock();
256
257         // Easy cases first
258         if state.disconnected { return Err(Disconnected) }
259         if state.buf.size() == 0 { return Err(Empty) }
260
261         // Be sure to wake up neighbors
262         let ret = Ok(state.buf.dequeue());
263         self.wakeup_senders(false, guard, state);
264
265         return ret;
266     }
267
268     // Wake up pending senders after some data has been received
269     //
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,
274                       guard: LockGuard,
275                       state: &mut State<T>) {
276         let pending_sender1: Option<BlockedTask> = state.queue.dequeue();
277
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) {
283                 NoneBlocked => None,
284                 BlockedReceiver(..) => unreachable!(),
285                 BlockedSender(task) => {
286                     state.canceled.take();
287                     Some(task)
288                 }
289             }
290         } else {
291             None
292         };
293         mem::drop((state, guard));
294
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()));
298     }
299
300     // Prepares this shared packet for a channel clone, essentially just bumping
301     // a refcount.
302     pub fn clone_chan(&self) {
303         self.channels.fetch_add(1, atomics::SeqCst);
304     }
305
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) {
309             1 => {}
310             _ => return
311         }
312
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) {
318             NoneBlocked => {}
319             BlockedSender(..) => unreachable!(),
320             BlockedReceiver(task) => wakeup(task, guard),
321         }
322     }
323
324     pub fn drop_port(&self) {
325         let (guard, state) = self.lock();
326
327         if state.disconnected { return }
328         state.disconnected = true;
329
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
334         // prevent deadlock.
335         let _data = if state.cap != 0 {
336             mem::replace(&mut state.buf.buf, Vec::new())
337         } else {
338             Vec::new()
339         };
340         let mut queue = mem::replace(&mut state.queue, Queue {
341             head: 0 as *mut Node,
342             tail: 0 as *mut Node,
343         });
344
345         let waiter = match mem::replace(&mut state.blocker, NoneBlocked) {
346             NoneBlocked => None,
347             BlockedSender(task) => {
348                 *state.canceled.take_unwrap() = true;
349                 Some(task)
350             }
351             BlockedReceiver(..) => unreachable!(),
352         };
353         mem::drop((state, guard));
354
355         loop {
356             match queue.dequeue() {
357                 Some(task) => { task.wake().map(|t| t.reawaken()); }
358                 None => break,
359             }
360         }
361         waiter.map(|t| t.wake().map(|t| t.reawaken()));
362     }
363
364     ////////////////////////////////////////////////////////////////////////////
365     // select implementation
366     ////////////////////////////////////////////////////////////////////////////
367
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
373     }
374
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 {
380             Err(task)
381         } else {
382             match mem::replace(&mut state.blocker, BlockedReceiver(task)) {
383                 NoneBlocked => {}
384                 BlockedSender(..) => unreachable!(),
385                 BlockedReceiver(..) => unreachable!(),
386             }
387             Ok(())
388         }
389     }
390
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.
393     //
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) {
398             NoneBlocked => true,
399             BlockedSender(task) => {
400                 state.blocker = BlockedSender(task);
401                 true
402             }
403             BlockedReceiver(task) => { task.trash(); false }
404         }
405     }
406 }
407
408 #[unsafe_destructor]
409 impl<T: Send> Drop for Packet<T> {
410     fn drop(&mut self) {
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());
415     }
416 }
417
418
419 ////////////////////////////////////////////////////////////////////////////////
420 // Buffer, a simple ring buffer backed by Vec<T>
421 ////////////////////////////////////////////////////////////////////////////////
422
423 impl<T> Buffer<T> {
424     fn enqueue(&mut self, t: T) {
425         let pos = (self.start + self.size) % self.buf.len();
426         self.size += 1;
427         let prev = mem::replace(self.buf.get_mut(pos), Some(t));
428         assert!(prev.is_none());
429     }
430
431     fn dequeue(&mut self) -> T {
432         let start = self.start;
433         self.size -= 1;
434         self.start = (self.start + 1) % self.buf.len();
435         self.buf.get_mut(start).take_unwrap()
436     }
437
438     fn size(&self) -> uint { self.size }
439     fn cap(&self) -> uint { self.buf.len() }
440 }
441
442 ////////////////////////////////////////////////////////////////////////////////
443 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
444 ////////////////////////////////////////////////////////////////////////////////
445
446 impl Queue {
447     fn enqueue(&mut self, lock: &NativeMutex) {
448         let task: ~Task = Local::take();
449         let mut node = Node {
450             task: None,
451             next: 0 as *mut Node,
452         };
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;
458             } else {
459                 unsafe {
460                     (*self.tail).next = &mut node as *mut Node;
461                     self.tail = &mut node as *mut Node;
462                 }
463             }
464             unsafe { lock.unlock_noguard(); }
465             Ok(())
466         });
467         unsafe { lock.lock_noguard(); }
468         assert!(node.next.is_null());
469     }
470
471     fn dequeue(&mut self) -> Option<BlockedTask> {
472         if self.head.is_null() {
473             return None
474         }
475         let node = self.head;
476         self.head = unsafe { (*node).next };
477         if self.head.is_null() {
478             self.tail = 0 as *mut Node;
479         }
480         unsafe {
481             (*node).next = 0 as *mut Node;
482             Some((*node).task.take_unwrap())
483         }
484     }
485 }