Debian Codegraph @

thirdparty/lockstdvector.h

raw
1 // just a thread safe queue
2 // actually using std::vector instead of std::queue to limit overheads
3 // see http://stackoverflow.com/questions/14784551/c-stl-queue-memory-usage-compared-to-vector
4
5 // adapted from:
6 // https://raw.githubusercontent.com/cameron314/concurrentqueue/master/benchmarks/stdqueue.h
7 // ©2014 Cameron Desrochers.
8
9 #pragma once
10
11 #include <vector>
12
13
14 // Simple wrapper around std::queue (not thread safe) - RC: made it thread safe
15 template<typename T>
16 class LockStdVector
17 {
18
19 public:
20
21 LockStdVector()
22 {
23 nb_items = 0;
24 }
25
26 template<typename U>
27 inline bool enqueue(U&& item)
28 {
29 std::lock_guard<std::mutex> guard(mutex);
30 unsigned long size = v.size();
31 v.push_back(std::forward<U>(item));
32 nb_items ++;
33 return true;
34 }
35
36 inline bool try_dequeue(T& item)
37 {
38 std::lock_guard<std::mutex> guard(mutex);
39 if (nb_items == 0) {
40 return false;
41 }
42
43 item = std::move(v.back());
44 v.pop_back();
45 nb_items--;
46 return true;
47 }
48
49 unsigned long size_approx()
50 {
51 return v.size();
52 }
53
54 unsigned long overhead_per_element()
55 {
56 return 0 ;
57 }
58 private:
59 std::vector<T> v;
60 mutable std::mutex mutex;
61 unsigned long nb_items;
62 };