xref: /nrf52832-nimble/packages/NimBLE-latest/porting/npl/linux/src/wqueue.h (revision 042d53a763ad75cb1465103098bb88c245d95138)
1 /*
2    wqueue.h
3    Worker thread queue based on the Standard C++ library list
4    template class.
5    ------------------------------------------
6    Copyright (c) 2013 Vic Hargrave
7    Licensed under the Apache License, Version 2.0 (the "License");
8    you may not use this file except in compliance with the License.
9    You may obtain a copy of the License at
10        http://www.apache.org/licenses/LICENSE-2.0
11    Unless required by applicable law or agreed to in writing, software
12    distributed under the License is distributed on an "AS IS" BASIS,
13    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14    See the License for the specific language governing permissions and
15    limitations under the License.
16 */
17 
18 // https://vichargrave.github.io/articles/2013-01/multithreaded-work-queue-in-cpp
19 // https://github.com/vichargrave/wqueue/blob/master/wqueue.h
20 
21 
22 #ifndef __wqueue_h__
23 #define __wqueue_h__
24 
25 #include <pthread.h>
26 #include <list>
27 
28 using namespace std;
29 
30 template <typename T> class wqueue
31 {
32     list<T>         m_queue;
33     pthread_mutex_t m_mutex;
34     pthread_cond_t  m_condv;
35 
36 public:
wqueue()37     wqueue()
38     {
39         pthread_mutexattr_t attr;
40         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
41         pthread_mutex_init(&m_mutex, &attr);
42         pthread_cond_init(&m_condv, NULL);
43     }
44 
~wqueue()45     ~wqueue() {
46         pthread_mutex_destroy(&m_mutex);
47         pthread_cond_destroy(&m_condv);
48     }
49 
put(T item)50     void put(T item) {
51         pthread_mutex_lock(&m_mutex);
52         m_queue.push_back(item);
53         pthread_cond_signal(&m_condv);
54         pthread_mutex_unlock(&m_mutex);
55     }
56 
get(uint32_t tmo)57     T get(uint32_t tmo) {
58         pthread_mutex_lock(&m_mutex);
59         if (tmo) {
60             while (m_queue.size() == 0) {
61                 pthread_cond_wait(&m_condv, &m_mutex);
62             }
63         }
64 
65         T item = NULL;
66 
67         if (m_queue.size() != 0) {
68             item = m_queue.front();
69             m_queue.pop_front();
70         }
71 
72         pthread_mutex_unlock(&m_mutex);
73         return item;
74     }
75 
size()76     int size() {
77         pthread_mutex_lock(&m_mutex);
78         int size = m_queue.size();
79         pthread_mutex_unlock(&m_mutex);
80         return size;
81     }
82 };
83 
84 #endif
85