# ms_queue.rs.html -- source
Source to the Rust file `/Users/travis/.cargo/registry/src/github.com-1ecc6299db9ec823/crossbeam-0.3.2/src/sync/ms_queue.rs`.
Keywords: rust, rustlang, rust-lang

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526

    use std::sync::atomic::Ordering::{Acquire, Release, Relaxed};
    use std::sync::atomic::AtomicBool;
    use std::{ptr, mem};
    use std::thread::{self, Thread};

    use epoch::{self, Atomic, Owned, Shared};
    use CachePadded;

    /// A Michael-Scott lock-free queue, with support for blocking `pop`s.
    ///
    /// Usable with any number of producers and consumers.
    // The representation here is a singly-linked list, with a sentinel
    // node at the front. In general the `tail` pointer may lag behind the
    // actual tail. Non-sentinel nodes are either all `Data` or all
    // `Blocked` (requests for data from blocked threads).
    #[derive(Debug)]
    pub struct MsQueue<T> {
        head: CachePadded<Atomic<Node<T>>>,
        tail: CachePadded<Atomic<Node<T>>>,
    }

    #[derive(Debug)]
    struct Node<T> {
        payload: Payload<T>,
        next: Atomic<Node<T>>,
    }

    #[derive(Debug)]
    enum Payload<T> {
        /// A node with actual data that can be popped.
        Data(T),
        /// A node representing a blocked request for data.
        Blocked(*mut Signal<T>),
    }

    /// A blocked request for data, which includes a slot to write the data.
    #[derive(Debug)]
    struct Signal<T> {
        /// Thread to unpark when data is ready.
        thread: Thread,
        /// The actual data, when available.
        data: Option<T>,
        /// Is the data ready? Needed to cope with spurious wakeups.
        ready: AtomicBool,
    }

    impl<T> Node<T> {
        fn is_data(&self) -> bool {
            if let Payload::Data(_) = self.payload { true } else { false }
        }
    }

    // Any particular `T` should never accessed concurrently, so no need
    // for Sync.
    unsafe impl<T: Send> Sync for MsQueue<T> {}
    unsafe impl<T: Send> Send for MsQueue<T> {}

    impl<T> MsQueue<T> {
        /// Create a new, empty queue.
        pub fn new() -> MsQueue<T> {
            let q = MsQueue {
                head: CachePadded::new(Atomic::null()),
                tail: CachePadded::new(Atomic::null()),
            };
            let sentinel = Owned::new(Node {
                payload: Payload::Data(unsafe { mem::uninitialized() }),
                next: Atomic::null(),
            });
            let guard = epoch::pin();
            let sentinel = q.head.store_and_ref(sentinel, Relaxed, &guard);
            q.tail.store_shared(Some(sentinel), Relaxed);
            q
        }

        #[inline(always)]
        /// Attempt to atomically place `n` into the `next` pointer of `onto`.
        ///
        /// If unsuccessful, returns ownership of `n`, possibly updating
        /// the queue's `tail` pointer.
        fn push_internal(&self,
                         guard: &epoch::Guard,
                         onto: Shared<Node<T>>,
                         n: Owned<Node<T>>)
                         -> Result<(), Owned<Node<T>>>
        {
            // is `onto` the actual tail?
            if let Some(next) = onto.next.load(Acquire, guard) {
                // if not, try to "help" by moving the tail pointer forward
                self.tail.cas_shared(Some(onto), Some(next), Release);
                Err(n)
            } else {
                // looks like the actual tail; attempt to link in `n`
                onto.next.cas_and_ref(None, n, Release, guard).map(|shared| {
                    // try to move the tail pointer forward
                    self.tail.cas_shared(Some(onto), Some(shared), Release);
                })
            }
        }

        /// Add `t` to the back of the queue, possibly waking up threads
        /// blocked on `pop`.
        pub fn push(&self, t: T) {
            /// We may or may not need to allocate a node; once we do,
            /// we cache that allocation.
            enum Cache<T> {
                Data(T),
                Node(Owned<Node<T>>),
            }

            impl<T> Cache<T> {
                /// Extract the node if cached, or allocate if not.
                fn into_node(self) -> Owned<Node<T>> {
                    match self {
                        Cache::Data(t) => {
                            Owned::new(Node {
                                payload: Payload::Data(t),
                                next: Atomic::null()
                            })
                        }
                        Cache::Node(n) => n
                    }
                }

                /// Extract the data from the cache, deallocating any cached node.
                fn into_data(self) -> T {
                    match self {
                        Cache::Data(t) => t,
                        Cache::Node(node) => {
                            match node.into_inner().payload {
                                Payload::Data(t) => t,
                                _ => unreachable!(),
                            }
                        }
                    }
                }
            }

            let mut cache = Cache::Data(t); // don't allocate up front
            let guard = epoch::pin();

            loop {
                // We push onto the tail, so we'll start optimistically by looking
                // there first.
                let tail = self.tail.load(Acquire, &guard).unwrap();

                // Is the queue in Data mode (empty queues can be viewed as either mode)?
                if tail.is_data() ||
                    self.head.load(Relaxed, &guard).unwrap().as_raw() == tail.as_raw()
                {
                    // Attempt to push onto the `tail` snapshot; fails if
                    // `tail.next` has changed, which will always be the case if the
                    // queue has transitioned to blocking mode.
                    match self.push_internal(&guard, tail, cache.into_node()) {
                        Ok(_) => return,
                        Err(n) => {
                            // replace the cache, retry whole thing
                            cache = Cache::Node(n)
                        }
                    }
                } else {
                    // Queue is in blocking mode. Attempt to unblock a thread.
                    let head = self.head.load(Acquire, &guard).unwrap();
                    // Get a handle on the first blocked node. Racy, so queue might
                    // be empty or in data mode by the time we see it.
                    let request = head.next.load(Acquire, &guard).and_then(|next| {
                        match next.payload {
                            Payload::Blocked(signal) => Some((next, signal)),
                            Payload::Data(_) => None,
                        }
                    });
                    if let Some((blocked_node, signal)) = request {
                        // race to dequeue the node
                        if self.head.cas_shared(Some(head), Some(blocked_node), Release) {
                            unsafe {
                                // signal the thread
                                (*signal).data = Some(cache.into_data());
                                let thread = (*signal).thread.clone();

                                (*signal).ready.store(true, Release);
                                thread.unpark();
                                guard.unlinked(head);
                                return;
                            }
                        }
                    }
                }
            }
        }

        #[inline(always)]
        // Attempt to pop a data node. `Ok(None)` if queue is empty or in blocking
        // mode; `Err(())` if lost race to pop.
        fn pop_internal(&self, guard: &epoch::Guard) -> Result<Option<T>, ()> {
            let head = self.head.load(Acquire, guard).unwrap();
            if let Some(next) = head.next.load(Acquire, guard) {
                if let Payload::Data(ref t) = next.payload {
                    unsafe {
                        if self.head.cas_shared(Some(head), Some(next), Release) {
                            guard.unlinked(head);
                            Ok(Some(ptr::read(t)))
                        } else {
                            Err(())
                        }
                    }
                } else {
                    Ok(None)
                }
            } else {
                Ok(None)
            }
        }

        /// Check if this queue is empty.
        pub fn is_empty(&self) -> bool {
            let guard = epoch::pin();
            let head = self.head.load(Acquire, &guard).unwrap();

            if let Some(next) = head.next.load(Acquire, &guard) {
                if let Payload::Data(_) = next.payload {
                    false
                } else {
                    true
                }
            } else {
                true
            }
        }

        /// Attempt to dequeue from the front.
        ///
        /// Returns `None` if the queue is observed to be empty.
        pub fn try_pop(&self) -> Option<T> {
            let guard = epoch::pin();
            loop {
                if let Ok(r) = self.pop_internal(&guard) {
                    return r;
                }
            }
        }

        /// Dequeue an element from the front of the queue, blocking if the queue is
        /// empty.
        pub fn pop(&self) -> T {
            let guard = epoch::pin();

            // Fast path: keep retrying until we observe that the queue has no data,
            // avoiding the allocation of a blocked node.
            loop {
                match self.pop_internal(&guard) {
                    Ok(Some(r)) => {
                        return r;
                    }
                    Ok(None) => {
                        break;
                    }
                    Err(()) => {}
                }
            }

            // The signal gets to live on the stack, since this stack frame will be
            // blocked until receiving the signal.
            let mut signal = Signal {
                thread: thread::current(),
                data: None,
                ready: AtomicBool::new(false),
            };

            // Go ahead and allocate the blocked node; chances are, we'll need it.
            let mut node = Owned::new(Node {
                payload: Payload::Blocked(&mut signal),
                next: Atomic::null(),
            });

            loop {
                // try a normal pop
                if let Ok(Some(r)) = self.pop_internal(&guard) {
                    return r;
                }

                // At this point, we believe the queue is empty/blocked.
                // Snapshot the tail, onto which we want to push a blocked node.
                let tail = self.tail.load(Acquire, &guard).unwrap();

                // Double-check that we're in blocking mode
                if tail.is_data() {
                    // The current tail is in data mode, so we probably need to abort.
                    // BUT, it might be the sentinel, so check for that first.
                    let head = self.head.load(Relaxed, &guard).unwrap();
                    if tail.is_data() && tail.as_raw() != head.as_raw() { continue; }
                }

                // At this point, the tail snapshot is either a blocked node deep in
                // the queue, the sentinel, or no longer accessible from the queue.
                // In *ALL* of these cases, if we succeed in pushing onto the
                // snapshot, we know we are maintaining the core invariant: all
                // reachable, non-sentinel nodes have the same payload mode, in this
                // case, blocked.
                match self.push_internal(&guard, tail, node) {
                    Ok(()) => {
                        while !signal.ready.load(Acquire) {
                            thread::park();
                        }
                        return signal.data.unwrap();
                    }
                    Err(n) => {
                        node = n;
                    }
                }
            }
        }
    }

    impl<T> Drop for MsQueue<T> {
        fn drop(&mut self) {
            while self.try_pop().is_some() {}

            // Destroy the remaining sentinel node.
            let guard = epoch::pin();
            let sentinel = self.head.load(Relaxed, &guard).unwrap().as_raw();
            unsafe {
                drop(Vec::from_raw_parts(sentinel, 0, 1));
            }
        }
    }

    #[cfg(test)]
    mod test {
        const CONC_COUNT: i64 = 1000000;

        use scope;
        use super::*;

        #[test]
        fn push_try_pop_1() {
            let q: MsQueue<i64> = MsQueue::new();
            assert!(q.is_empty());
            q.push(37);
            assert!(!q.is_empty());
            assert_eq!(q.try_pop(), Some(37));
            assert!(q.is_empty());
        }

        #[test]
        fn push_try_pop_2() {
            let q: MsQueue<i64> = MsQueue::new();
            assert!(q.is_empty());
            q.push(37);
            q.push(48);
            assert_eq!(q.try_pop(), Some(37));
            assert!(!q.is_empty());
            assert_eq!(q.try_pop(), Some(48));
            assert!(q.is_empty());
        }

        #[test]
        fn push_try_pop_many_seq() {
            let q: MsQueue<i64> = MsQueue::new();
            assert!(q.is_empty());
            for i in 0..200 {
                q.push(i)
            }
            assert!(!q.is_empty());
            for i in 0..200 {
                assert_eq!(q.try_pop(), Some(i));
            }
            assert!(q.is_empty());
        }

        #[test]
        fn push_pop_1() {
            let q: MsQueue<i64> = MsQueue::new();
            assert!(q.is_empty());
            q.push(37);
            assert!(!q.is_empty());
            assert_eq!(q.pop(), 37);
            assert!(q.is_empty());
        }

        #[test]
        fn push_pop_2() {
            let q: MsQueue<i64> = MsQueue::new();
            q.push(37);
            q.push(48);
            assert_eq!(q.pop(), 37);
            assert_eq!(q.pop(), 48);
        }

        #[test]
        fn push_pop_many_seq() {
            let q: MsQueue<i64> = MsQueue::new();
            assert!(q.is_empty());
            for i in 0..200 {
                q.push(i)
            }
            assert!(!q.is_empty());
            for i in 0..200 {
                assert_eq!(q.pop(), i);
            }
            assert!(q.is_empty());
        }

        #[test]
        fn push_try_pop_many_spsc() {
            let q: MsQueue<i64> = MsQueue::new();
            assert!(q.is_empty());

            scope(|scope| {
                scope.spawn(|| {
                    let mut next = 0;

                    while next < CONC_COUNT {
                        if let Some(elem) = q.try_pop() {
                            assert_eq!(elem, next);
                            next += 1;
                        }
                    }
                });

                for i in 0..CONC_COUNT {
                    q.push(i)
                }
            });
        }

        #[test]
        fn push_try_pop_many_spmc() {
            fn recv(_t: i32, q: &MsQueue<i64>) {
                let mut cur = -1;
                for _i in 0..CONC_COUNT {
                    if let Some(elem) = q.try_pop() {
                        assert!(elem > cur);
                        cur = elem;

                        if cur == CONC_COUNT - 1 { break }
                    }
                }
            }

            let q: MsQueue<i64> = MsQueue::new();
            assert!(q.is_empty());
            let qr = &q;
            scope(|scope| {
                for i in 0..3 {
                    scope.spawn(move || recv(i, qr));
                }

                scope.spawn(|| {
                    for i in 0..CONC_COUNT {
                        q.push(i);
                    }
                })
            });
        }

        #[test]
        fn push_try_pop_many_mpmc() {
            enum LR { Left(i64), Right(i64) }

            let q: MsQueue<LR> = MsQueue::new();
            assert!(q.is_empty());

            scope(|scope| {
                for _t in 0..2 {
                    scope.spawn(|| {
                        for i in CONC_COUNT-1..CONC_COUNT {
                            q.push(LR::Left(i))
                        }
                    });
                    scope.spawn(|| {
                        for i in CONC_COUNT-1..CONC_COUNT {
                            q.push(LR::Right(i))
                        }
                    });
                    scope.spawn(|| {
                        let mut vl = vec![];
                        let mut vr = vec![];
                        for _i in 0..CONC_COUNT {
                            match q.try_pop() {
                                Some(LR::Left(x)) => vl.push(x),
                                Some(LR::Right(x)) => vr.push(x),
                                _ => {}
                            }
                        }

                        let mut vl2 = vl.clone();
                        let mut vr2 = vr.clone();
                        vl2.sort();
                        vr2.sort();

                        assert_eq!(vl, vl2);
                        assert_eq!(vr, vr2);
                    });
                }
            });
        }

        #[test]
        fn push_pop_many_spsc() {
            let q: MsQueue<i64> = MsQueue::new();

            scope(|scope| {
                scope.spawn(|| {
                    let mut next = 0;
                    while next < CONC_COUNT {
                        assert_eq!(q.pop(), next);
                        next += 1;
                    }
                });

                for i in 0..CONC_COUNT {
                    q.push(i)
                }
            });
            assert!(q.is_empty());
        }

        #[test]
        fn is_empty_dont_pop() {
            let q: MsQueue<i64> = MsQueue::new();
            q.push(20);
            q.push(20);
            assert!(!q.is_empty());
            assert!(!q.is_empty());
            assert!(q.try_pop().is_some());
        }
    }

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)