Jpp  18.3.0
the software that should make you happy
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
ptr_dispatcher.hh
Go to the documentation of this file.
1 #ifndef PTR_DISPATCHER_HH
2 #define PTR_DISPATCHER_HH
3 
4 #include <pthread.h>
5 #include <deque>
6 #include <boost/atomic.hpp>
7 
8 /**
9  * \author cpellegrino
10  */
11 
13 {
14  std::deque<void*> m_queue;
15 
16  pthread_mutex_t m_mutex;
17 
18  pthread_cond_t m_cond;
19 
20  boost::atomic<bool> m_status;
21 
22  public:
23 
25  :
26  m_status(true)
27  {
28  pthread_mutex_init(&m_mutex, 0);
29  pthread_cond_init (&m_cond, 0);
30  }
31 
33  {
34  close();
35  pthread_mutex_destroy(&m_mutex);
36  pthread_cond_destroy(&m_cond);
37  }
38 
39  void close()
40  {
41  m_status = false;
42  lock();
43  signal();
44  unlock();
45  }
46 
47  void signal()
48  {
49  pthread_cond_signal(&m_cond);
50  }
51 
52  void lock()
53  {
54  pthread_mutex_lock(&m_mutex);
55  }
56 
57  void unlock()
58  {
59  pthread_mutex_unlock(&m_mutex);
60  }
61 
62  void* get_nolock()
63  {
64  if (m_queue.empty() || !m_status)
65  {
66  return 0;
67  }
68 
69  void* pointer = m_queue.front();
70  m_queue.pop_front();
71  return pointer;
72  }
73 
74  void* get()
75  {
76  if (!m_status)
77  {
78  return 0;
79  }
80 
81  lock();
82  wait();
83 
84  void* pointer = 0;
85 
86  if (m_queue.size())
87  {
88  pointer = m_queue.front();
89  m_queue.pop_front();
90  }
91 
92  unlock();
93  return pointer;
94  }
95 
96  void put_nolock(void* pointer)
97  {
98  if (m_status)
99  {
100  m_queue.push_back(pointer);
101  }
102  }
103 
104  void put(void* pointer)
105  {
106  if (m_status)
107  {
108  lock();
109  m_queue.push_back(pointer);
110  signal();
111  unlock();
112  }
113  }
114 
115  private:
116 
117  void wait()
118  {
119  while (m_queue.empty() && m_status)
120  {
121  if (pthread_cond_wait(&m_cond, &m_mutex) == EINVAL)
122  {
123  break;
124  }
125  }
126  }
127 
128 };
129 
130 #endif // PTR_DISPATCHER_HH
void put(void *pointer)
boost::atomic< bool > m_status
pthread_cond_t m_cond
std::deque< void * > m_queue
void put_nolock(void *pointer)
pthread_mutex_t m_mutex
void * get_nolock()