~ttt/async

ref: 3f9709cd0f81e1a7025effd4125a781b2a4048b9 async/BlockingQueue/include/blocking_queue.h -rw-r--r-- 1.1 KiB
3f9709cd — Tomasz Kłak Merged mwaga/async into master 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
54
55
56
57
58
59
60
61
62
63
64
#ifndef BLOCKING_QUEUE_H
#define BLOCKING_QUEUE_H

template <typename T,
          typename Queue,
          typename Lockable,
          typename ConditionVariable,
          typename LockGuard>
class blocking_queue
{
public:
    blocking_queue(Queue& queue,
                  Lockable& mutex,
                  ConditionVariable& conditionVariable)
        : queue(queue),
          mutex(mutex),
          conditionVariable(conditionVariable)
    {}

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

            queue.push(task);
        }

        conditionVariable.notify_one();
    }

    T wait_and_pop()
    {
        LockGuard lock(mutex);

        while (queue.empty())
        {
            conditionVariable.wait(lock);
        }

        T task = queue.front();

        queue.pop();

        return task;
    }

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

            queue.push(task);
        }

        conditionVariable.notify_all();
    }

private:
    Queue& queue;
    Lockable& mutex;
    ConditionVariable& conditionVariable;
};

#endif // BLOCKING_QUEUE_H