aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/threading/queue/mpsc_intrusive_unordered.cpp
blob: 3bb1a04f7e97a238346da22c03392e1616d19798 (plain) (blame)
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
#include "mpsc_intrusive_unordered.h"
#include <util/system/atomic.h>

namespace NThreading {
    void TMPSCIntrusiveUnordered::Push(TIntrusiveNode* node) noexcept {
        auto head = AtomicGet(HeadForCaS);
        for (ui32 i = NUMBER_OF_TRIES_FOR_CAS; i-- > 0;) {
            // no ABA here, because Next is exactly head
            // it does not matter how many travels head was made/
            node->Next = head;
            auto prev = AtomicGetAndCas(&HeadForCaS, node, head);
            if (head == prev) {
                return;
            }
            head = prev;
        }
        // boring of trying to do cas, let's just swap

        // no need for atomic here, because the next is atomic swap
        node->Next = 0;

        head = AtomicSwap(&HeadForSwap, node);
        if (head != nullptr) {
            AtomicSet(node->Next, head);
        } else {
            // consumer must know if no other thread may access the memory,
            // setting Next to node is a way to notify consumer
            AtomicSet(node->Next, node);
        }
    }

    TIntrusiveNode* TMPSCIntrusiveUnordered::PopMany() noexcept {
        if (NotReadyChain == nullptr) {
            auto head = AtomicSwap(&HeadForSwap, nullptr);
            NotReadyChain = head;
        }

        if (NotReadyChain != nullptr) {
            auto next = AtomicGet(NotReadyChain->Next);
            if (next != nullptr) {
                auto ready = NotReadyChain;
                TIntrusiveNode* cut;
                do {
                    cut = NotReadyChain;
                    NotReadyChain = next;
                    next = AtomicGet(NotReadyChain->Next);
                    if (next == NotReadyChain) {
                        cut = NotReadyChain;
                        NotReadyChain = nullptr;
                        break;
                    }
                } while (next != nullptr);
                cut->Next = nullptr;
                return ready;
            }
        }

        if (AtomicGet(HeadForCaS) != nullptr) {
            return AtomicSwap(&HeadForCaS, nullptr);
        }
        return nullptr;
    }

    TIntrusiveNode* TMPSCIntrusiveUnordered::Pop() noexcept {
        if (PopOneQueue != nullptr) {
            auto head = PopOneQueue;
            PopOneQueue = PopOneQueue->Next;
            return head;
        }

        PopOneQueue = PopMany();
        if (PopOneQueue != nullptr) {
            auto head = PopOneQueue;
            PopOneQueue = PopOneQueue->Next;
            return head;
        }
        return nullptr;
    }
}