blob: 256e8e33cdd147f246a2ef0347c922a19f442e61 (
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
|
#pragma once
#include <queue>
#include <pthread.h>
namespace Balau {
template<class T>
class Queue;
class Lock {
public:
Lock();
~Lock() { pthread_mutex_destroy(&m_lock); }
void enter() { pthread_mutex_lock(&m_lock); }
void leave() { pthread_mutex_unlock(&m_lock); }
private:
pthread_mutex_t m_lock;
template<class T>
friend class Queue;
};
class ThreadHelper;
class Thread {
public:
virtual ~Thread();
void threadStart();
void * join();
protected:
Thread() : m_joined(false) { }
virtual void * proc() = 0;
private:
pthread_t m_thread;
bool m_joined;
friend class ThreadHelper;
};
template<class T>
class Queue {
public:
Queue() { pthread_cond_init(&m_cond, NULL); }
~Queue() { while (size()) pop(); pthread_cond_destroy(&m_cond); }
void push(T & t) {
m_lock.enter();
m_queue.push(t);
pthread_cond_signal(&m_cond);
m_lock.leave();
}
T pop() {
m_lock.enter();
if (m_queue.size() == 0)
pthread_cond_wait(&m_cond, &m_lock.m_lock);
T t = m_queue.front();
m_queue.pop();
m_lock.leave();
return t;
}
int size() {
int r;
m_lock.enter();
r = m_queue.size();
m_lock.leave();
return r;
}
private:
std::queue<T> m_queue;
Lock m_lock;
pthread_cond_t m_cond;
};
};
|