]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/mpsc/sync.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / libstd / sync / mpsc / 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 panic 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 core::prelude::*;
37
38 pub use self::Failure::*;
39 use self::Blocker::*;
40
41 use vec::Vec;
42 use core::mem;
43
44 use sync::atomic::{Ordering, AtomicUint};
45 use sync::mpsc::blocking::{self, WaitToken, SignalToken};
46 use sync::mpsc::select::StartResult::{self, Installed, Abort};
47 use sync::{Mutex, MutexGuard};
48
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: AtomicUint,
53
54     lock: Mutex<State<T>>,
55 }
56
57 unsafe impl<T:Send> Send for Packet<T> { }
58
59 unsafe impl<T:Send> Sync for Packet<T> { }
60
61 struct State<T> {
62     disconnected: bool, // Is the channel disconnected yet?
63     queue: Queue,       // queue of senders waiting to send data
64     blocker: Blocker,   // currently blocked task on this channel
65     buf: Buffer<T>,     // storage for buffered messages
66     cap: uint,          // capacity of this channel
67
68     /// A curious flag used to indicate whether a sender failed or succeeded in
69     /// blocking. This is used to transmit information back to the task that it
70     /// must dequeue its message from the buffer because it was not received.
71     /// This is only relevant in the 0-buffer case. This obviously cannot be
72     /// safely constructed, but it's guaranteed to always have a valid pointer
73     /// value.
74     canceled: Option<&'static mut bool>,
75 }
76
77 unsafe impl<T: Send> Send for State<T> {}
78
79 /// Possible flavors of threads who can be blocked on this channel.
80 enum Blocker {
81     BlockedSender(SignalToken),
82     BlockedReceiver(SignalToken),
83     NoneBlocked
84 }
85
86 /// Simple queue for threading tasks together. Nodes are stack-allocated, so
87 /// this structure is not safe at all
88 struct Queue {
89     head: *mut Node,
90     tail: *mut Node,
91 }
92
93 struct Node {
94     token: Option<SignalToken>,
95     next: *mut Node,
96 }
97
98 unsafe impl Send for Node {}
99
100 /// A simple ring-buffer
101 struct Buffer<T> {
102     buf: Vec<Option<T>>,
103     start: uint,
104     size: uint,
105 }
106
107 #[derive(Show)]
108 pub enum Failure {
109     Empty,
110     Disconnected,
111 }
112
113 /// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
114 /// in the meantime. This re-locks the mutex upon returning.
115 fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
116                          mut guard: MutexGuard<'b, State<T>>,
117                          f: fn(SignalToken) -> Blocker)
118                          -> MutexGuard<'a, State<T>>
119 {
120     let (wait_token, signal_token) = blocking::tokens();
121     match mem::replace(&mut guard.blocker, f(signal_token)) {
122         NoneBlocked => {}
123         _ => unreachable!(),
124     }
125     drop(guard);         // unlock
126     wait_token.wait();   // block
127     lock.lock().unwrap() // relock
128 }
129
130 /// Wakes up a thread, dropping the lock at the correct time
131 fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
132     // We need to be careful to wake up the waiting task *outside* of the mutex
133     // in case it incurs a context switch.
134     drop(guard);
135     token.signal();
136 }
137
138 impl<T: Send> Packet<T> {
139     pub fn new(cap: uint) -> Packet<T> {
140         Packet {
141             channels: AtomicUint::new(1),
142             lock: Mutex::new(State {
143                 disconnected: false,
144                 blocker: NoneBlocked,
145                 cap: cap,
146                 canceled: None,
147                 queue: Queue {
148                     head: 0 as *mut Node,
149                     tail: 0 as *mut Node,
150                 },
151                 buf: Buffer {
152                     buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
153                     start: 0,
154                     size: 0,
155                 },
156             }),
157         }
158     }
159
160     // wait until a send slot is available, returning locked access to
161     // the channel state.
162     fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
163         let mut node = Node { token: None, next: 0 as *mut Node };
164         loop {
165             let mut guard = self.lock.lock().unwrap();
166             // are we ready to go?
167             if guard.disconnected || guard.buf.size() < guard.buf.cap() {
168                 return guard;
169             }
170             // no room; actually block
171             let wait_token = guard.queue.enqueue(&mut node);
172             drop(guard);
173             wait_token.wait();
174         }
175     }
176
177     pub fn send(&self, t: T) -> Result<(), T> {
178         let mut guard = self.acquire_send_slot();
179         if guard.disconnected { return Err(t) }
180         guard.buf.enqueue(t);
181
182         match mem::replace(&mut guard.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 guard.cap == 0 => {
188                 let mut canceled = false;
189                 assert!(guard.canceled.is_none());
190                 guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
191                 let mut guard = wait(&self.lock, guard, BlockedSender);
192                 if canceled {Err(guard.buf.dequeue())} else {Ok(())}
193             }
194
195             // success, we buffered some data
196             NoneBlocked => Ok(()),
197
198             // success, someone's about to receive our buffered data.
199             BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
200
201             BlockedSender(..) => panic!("lolwut"),
202         }
203     }
204
205     pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
206         let mut guard = self.lock.lock().unwrap();
207         if guard.disconnected {
208             Err(super::TrySendError::Disconnected(t))
209         } else if guard.buf.size() == guard.buf.cap() {
210             Err(super::TrySendError::Full(t))
211         } else if guard.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 guard.blocker, NoneBlocked) {
215                 NoneBlocked => Err(super::TrySendError::Full(t)),
216                 BlockedSender(..) => unreachable!(),
217                 BlockedReceiver(token) => {
218                     guard.buf.enqueue(t);
219                     wakeup(token, guard);
220                     Ok(())
221                 }
222             }
223         } else {
224             // If the buffer has some space and the capacity isn't 0, then we
225             // just enqueue the data for later retrieval, ensuring to wake up
226             // any blocked receiver if there is one.
227             assert!(guard.buf.size() < guard.buf.cap());
228             guard.buf.enqueue(t);
229             match mem::replace(&mut guard.blocker, NoneBlocked) {
230                 BlockedReceiver(token) => wakeup(token, guard),
231                 NoneBlocked => {}
232                 BlockedSender(..) => unreachable!(),
233             }
234             Ok(())
235         }
236     }
237
238     // Receives a message from this channel
239     //
240     // When reading this, remember that there can only ever be one receiver at
241     // time.
242     pub fn recv(&self) -> Result<T, ()> {
243         let mut guard = self.lock.lock().unwrap();
244
245         // Wait for the buffer to have something in it. No need for a while loop
246         // because we're the only receiver.
247         let mut waited = false;
248         if !guard.disconnected && guard.buf.size() == 0 {
249             guard = wait(&self.lock, guard, BlockedReceiver);
250             waited = true;
251         }
252         if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
253
254         // Pick up the data, wake up our neighbors, and carry on
255         assert!(guard.buf.size() > 0);
256         let ret = guard.buf.dequeue();
257         self.wakeup_senders(waited, guard);
258         return Ok(ret);
259     }
260
261     pub fn try_recv(&self) -> Result<T, Failure> {
262         let mut guard = self.lock.lock().unwrap();
263
264         // Easy cases first
265         if guard.disconnected { return Err(Disconnected) }
266         if guard.buf.size() == 0 { return Err(Empty) }
267
268         // Be sure to wake up neighbors
269         let ret = Ok(guard.buf.dequeue());
270         self.wakeup_senders(false, guard);
271
272         return ret;
273     }
274
275     // Wake up pending senders after some data has been received
276     //
277     // * `waited` - flag if the receiver blocked to receive some data, or if it
278     //              just picked up some data on the way out
279     // * `guard` - the lock guard that is held over this channel's lock
280     fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
281         let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
282
283         // If this is a no-buffer channel (cap == 0), then if we didn't wait we
284         // need to ACK the sender. If we waited, then the sender waking us up
285         // was already the ACK.
286         let pending_sender2 = if guard.cap == 0 && !waited {
287             match mem::replace(&mut guard.blocker, NoneBlocked) {
288                 NoneBlocked => None,
289                 BlockedReceiver(..) => unreachable!(),
290                 BlockedSender(token) => {
291                     guard.canceled.take();
292                     Some(token)
293                 }
294             }
295         } else {
296             None
297         };
298         mem::drop(guard);
299
300         // only outside of the lock do we wake up the pending tasks
301         pending_sender1.map(|t| t.signal());
302         pending_sender2.map(|t| t.signal());
303     }
304
305     // Prepares this shared packet for a channel clone, essentially just bumping
306     // a refcount.
307     pub fn clone_chan(&self) {
308         self.channels.fetch_add(1, Ordering::SeqCst);
309     }
310
311     pub fn drop_chan(&self) {
312         // Only flag the channel as disconnected if we're the last channel
313         match self.channels.fetch_sub(1, Ordering::SeqCst) {
314             1 => {}
315             _ => return
316         }
317
318         // Not much to do other than wake up a receiver if one's there
319         let mut guard = self.lock.lock().unwrap();
320         if guard.disconnected { return }
321         guard.disconnected = true;
322         match mem::replace(&mut guard.blocker, NoneBlocked) {
323             NoneBlocked => {}
324             BlockedSender(..) => unreachable!(),
325             BlockedReceiver(token) => wakeup(token, guard),
326         }
327     }
328
329     pub fn drop_port(&self) {
330         let mut guard = self.lock.lock().unwrap();
331
332         if guard.disconnected { return }
333         guard.disconnected = true;
334
335         // If the capacity is 0, then the sender may want its data back after
336         // we're disconnected. Otherwise it's now our responsibility to destroy
337         // the buffered data. As with many other portions of this code, this
338         // needs to be careful to destroy the data *outside* of the lock to
339         // prevent deadlock.
340         let _data = if guard.cap != 0 {
341             mem::replace(&mut guard.buf.buf, Vec::new())
342         } else {
343             Vec::new()
344         };
345         let mut queue = mem::replace(&mut guard.queue, Queue {
346             head: 0 as *mut Node,
347             tail: 0 as *mut Node,
348         });
349
350         let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
351             NoneBlocked => None,
352             BlockedSender(token) => {
353                 *guard.canceled.take().unwrap() = true;
354                 Some(token)
355             }
356             BlockedReceiver(..) => unreachable!(),
357         };
358         mem::drop(guard);
359
360         loop {
361             match queue.dequeue() {
362                 Some(token) => { token.signal(); }
363                 None => break,
364             }
365         }
366         waiter.map(|t| t.signal());
367     }
368
369     ////////////////////////////////////////////////////////////////////////////
370     // select implementation
371     ////////////////////////////////////////////////////////////////////////////
372
373     // If Ok, the value is whether this port has data, if Err, then the upgraded
374     // port needs to be checked instead of this one.
375     pub fn can_recv(&self) -> bool {
376         let guard = self.lock.lock().unwrap();
377         guard.disconnected || guard.buf.size() > 0
378     }
379
380     // Attempts to start selection on this port. This can either succeed or fail
381     // because there is data waiting.
382     pub fn start_selection(&self, token: SignalToken) -> StartResult {
383         let mut guard = self.lock.lock().unwrap();
384         if guard.disconnected || guard.buf.size() > 0 {
385             Abort
386         } else {
387             match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
388                 NoneBlocked => {}
389                 BlockedSender(..) => unreachable!(),
390                 BlockedReceiver(..) => unreachable!(),
391             }
392             Installed
393         }
394     }
395
396     // Remove a previous selecting task from this port. This ensures that the
397     // blocked task will no longer be visible to any other threads.
398     //
399     // The return value indicates whether there's data on this port.
400     pub fn abort_selection(&self) -> bool {
401         let mut guard = self.lock.lock().unwrap();
402         match mem::replace(&mut guard.blocker, NoneBlocked) {
403             NoneBlocked => true,
404             BlockedSender(token) => {
405                 guard.blocker = BlockedSender(token);
406                 true
407             }
408             BlockedReceiver(token) => { drop(token); false }
409         }
410     }
411 }
412
413 #[unsafe_destructor]
414 impl<T: Send> Drop for Packet<T> {
415     fn drop(&mut self) {
416         assert_eq!(self.channels.load(Ordering::SeqCst), 0);
417         let mut guard = self.lock.lock().unwrap();
418         assert!(guard.queue.dequeue().is_none());
419         assert!(guard.canceled.is_none());
420     }
421 }
422
423
424 ////////////////////////////////////////////////////////////////////////////////
425 // Buffer, a simple ring buffer backed by Vec<T>
426 ////////////////////////////////////////////////////////////////////////////////
427
428 impl<T> Buffer<T> {
429     fn enqueue(&mut self, t: T) {
430         let pos = (self.start + self.size) % self.buf.len();
431         self.size += 1;
432         let prev = mem::replace(&mut self.buf[pos], Some(t));
433         assert!(prev.is_none());
434     }
435
436     fn dequeue(&mut self) -> T {
437         let start = self.start;
438         self.size -= 1;
439         self.start = (self.start + 1) % self.buf.len();
440         self.buf[start].take().unwrap()
441     }
442
443     fn size(&self) -> uint { self.size }
444     fn cap(&self) -> uint { self.buf.len() }
445 }
446
447 ////////////////////////////////////////////////////////////////////////////////
448 // Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
449 ////////////////////////////////////////////////////////////////////////////////
450
451 impl Queue {
452     fn enqueue(&mut self, node: &mut Node) -> WaitToken {
453         let (wait_token, signal_token) = blocking::tokens();
454         node.token = Some(signal_token);
455         node.next = 0 as *mut Node;
456
457         if self.tail.is_null() {
458             self.head = node as *mut Node;
459             self.tail = node as *mut Node;
460         } else {
461             unsafe {
462                 (*self.tail).next = node as *mut Node;
463                 self.tail = node as *mut Node;
464             }
465         }
466
467         wait_token
468     }
469
470     fn dequeue(&mut self) -> Option<SignalToken> {
471         if self.head.is_null() {
472             return None
473         }
474         let node = self.head;
475         self.head = unsafe { (*node).next };
476         if self.head.is_null() {
477             self.tail = 0 as *mut Node;
478         }
479         unsafe {
480             (*node).next = 0 as *mut Node;
481             Some((*node).token.take().unwrap())
482         }
483     }
484 }