~ttt/async

ref: e1d02f899cb6acf79f581a7a5f4f6ce9117cad27 async/BlockingQueue/include/blocking_queue.h -rw-r--r-- 955 bytes
e1d02f89 — Tomasz Klak simplified blocking_queue 8 years ago
                                                                                
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
#ifndef BLOCKING_QUEUE_H
#define BLOCKING_QUEUE_H

template <typename Queue,
          typename ConditionVariable,
          typename LockGuard>
class blocking_queue
{
public:
    using Element = typename Queue::value_type;

    void push_and_notify_one(Element task)
    {
        {
            LockGuard lock(mutex);

            queue.push(task);
        }

        conditionVariable.notify_one();
    }

    Element wait_and_pop()
    {
        LockGuard lock(mutex);

        conditionVariable.wait(lock, [&]{ return !queue.empty(); });

        Element task = queue.front();

        queue.pop();

        return task;
    }

    void push_and_notify_all(Element task)
    {
        {
            LockGuard lock(mutex);

            queue.push(task);
        }

        conditionVariable.notify_all();
    }

private:
    Queue queue;
    typename LockGuard::mutex_type mutex;
    ConditionVariable conditionVariable;
};

#endif // BLOCKING_QUEUE_H