summaryrefslogtreecommitdiff
path: root/include/common/MsgQueue.h
blob: 3ca740aa9d1ea0389a2b7391960d157c517736f2 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
 * msg-service
 *
 * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd. All rights reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

#ifndef __MsgThdSafeQ_H__
#define __MsgThdSafeQ_H__

#include <queue>
#include "MsgMutex.h"
#include <list>

template <typename T> class MsgThdSafeQ
{
public:
	MsgThdSafeQ(){};
	void pop_front ();
	bool front(T* qItem);
	void push_front(T const & input);
	void push_back(T const & input);
	int size();
	bool empty();
	void clear();
	bool checkExist(T const & qItem, bool(cmp)(T const &, T const &));
private:
	Mutex mx;
	std::list <T> q;
};

/*
	mx variable guarantees atomic operation in multi-threaded environment.
	For example, when a thread is executing Pop(), other threads
	trying to execute one of Pop, Push, Size, Empty are locked.
*/

template <typename T> void MsgThdSafeQ<T>::pop_front()
{
	MutexLocker lock(mx);
	if( q.empty() ) return;

	q.pop_front();
}

template <typename T> bool MsgThdSafeQ<T>::front(T* qItem)
{
	MutexLocker lock(mx);
	if( qItem == NULL || q.empty() )
		return false; // Fail

	*qItem = q.front(); // copy

	return true; // Success
}


template <typename T> void MsgThdSafeQ<T>::push_back(T const & qItem)
{
	MutexLocker lock(mx);
	q.push_back(qItem);
}

template <typename T> void MsgThdSafeQ<T>::push_front(T const & qItem)
{
	MutexLocker lock(mx);
	q.push_front(qItem);
}


template <typename T> int MsgThdSafeQ<T>::size()
{
	MutexLocker lock(mx);
	return q.size();
}

template <typename T> bool MsgThdSafeQ<T>::empty()
{
	MutexLocker lock(mx);
	return q.empty();
}

template <typename T> void MsgThdSafeQ<T>::clear()
{
	MutexLocker lock(mx);
	q.clear();
}

template <typename T> bool MsgThdSafeQ<T>::checkExist(T const & qItem, bool(cmp)(T const &, T const &))
{
	MutexLocker lock(mx);

	for(typename list<T>::iterator iterPos = q.begin(); iterPos != q.end(); ++iterPos) 	{

		if (cmp(qItem, *iterPos) == true)
			return true;
	}

	return false;
}

#endif // __MsgThdSafeQ_H__