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