File: lockstdqueue.h

package info (click to toggle)
bcalm 2.2.3-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 624 kB
  • sloc: cpp: 3,132; python: 314; sh: 87; makefile: 13
file content (51 lines) | stat: -rw-r--r-- 1,054 bytes parent folder | download | duplicates (5)
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
// just a thread safe queue, the most simple ever

// adapted from:
// https://raw.githubusercontent.com/cameron314/concurrentqueue/master/benchmarks/stdqueue.h
// ©2014 Cameron Desrochers.

#pragma once

#include <queue>


// Simple wrapper around std::queue (not thread safe) - RC: made it thread safe
template<typename T>
class LockStdQueue 
{
    
public:
    template<typename U>
    inline bool enqueue(U&& item)
    {
		std::lock_guard<std::mutex> guard(mutex);
        q.push(std::forward<U>(item));
        return true;
    }
    
    inline bool try_dequeue(T& item)
    {
		std::lock_guard<std::mutex> guard(mutex);
        if (q.empty()) {
            return false;
        }
        
        item = std::move(q.front());
        q.pop();
        return true;
    }
    
    unsigned long size_approx()
    {
        return q.size(); 
    }
	
    unsigned long overhead_per_element()
    {
        return 0; // I don't think anymore that's true. there must be some overhead
    }

private:
    std::queue<T> q;
	mutable std::mutex mutex;
};