libosmscout  1.1.1
WorkQueue.h
Go to the documentation of this file.
1 #ifndef OSMSCOUT_UTIL_WORKQUEUE_H
2 #define OSMSCOUT_UTIL_WORKQUEUE_H
3 
4 /*
5  This source is part of the libosmscout library
6  Copyright (C) 2015 Tim Teulings
7 
8  This library is free software; you can redistribute it and/or
9  modify it under the terms of the GNU Lesser General Public
10  License as published by the Free Software Foundation; either
11  version 2.1 of the License, or (at your option) any later version.
12 
13  This library is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  Lesser General Public License for more details.
17 
18  You should have received a copy of the GNU Lesser General Public
19  License along with this library; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 */
22 
23 #include <condition_variable>
24 #include <deque>
25 #include <future>
26 #include <memory>
27 #include <limits>
28 #include <thread>
29 
31 
32 namespace osmscout {
33 
34  template<typename R>
35  class WorkQueue
36  {
37  private:
38  using Task = std::packaged_task<R ()>;
39 
40  private:
41  std::mutex mutex;
42  std::condition_variable pushCondition;
43  std::condition_variable popCondition;
44  std::deque<Task> tasks;
45  size_t queueLimit=std::numeric_limits<size_t>::max();
46  bool running=true;
47 
48  public:
49  WorkQueue();
50 
51  explicit WorkQueue(size_t queueLimit);
52  ~WorkQueue();
53 
54  void PushTask(Task& task);
55  bool PopTask(Task& task);
56 
57  void Stop();
58  };
59 
60  template<class R>
61  WorkQueue<R>::WorkQueue() = default;
62 
63  template<class R>
64  WorkQueue<R>::WorkQueue(size_t queueLimit)
65  : queueLimit(queueLimit)
66  {
67  // no code
68  }
69 
70  template<class R>
71  WorkQueue<R>::~WorkQueue() = default;
72 
73  template<class R>
74  void WorkQueue<R>::PushTask(Task& task)
75  {
76  std::unique_lock lock(mutex);
77 
78  pushCondition.wait(lock,[this]{return tasks.size()<=queueLimit;});
79 
80  tasks.push_back(std::move(task));
81 
82  popCondition.notify_one();
83  }
84 
85  template<class R>
86  bool WorkQueue<R>::PopTask(Task& task)
87  {
88  std::unique_lock lock(mutex);
89 
90  popCondition.wait(lock,[this]{return !tasks.empty() || !running;});
91 
92  if (tasks.empty() &&
93  !running) {
94  return false;
95  }
96 
97  task=std::move(tasks.front());
98  tasks.pop_front();
99 
100  pushCondition.notify_one();
101 
102  return true;
103  }
104 
105  template<class R>
107  {
108  std::scoped_lock<std::mutex> lock(mutex);
109 
110  running=false;
111 
112  popCondition.notify_all();
113  }
114 }
115 
116 #endif
void PushTask(Task &task)
Definition: WorkQueue.h:74
void Stop()
Definition: WorkQueue.h:106
Definition: WorkQueue.h:35
Definition: Area.h:38
bool PopTask(Task &task)
Definition: WorkQueue.h:86