-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBlockQueue.h
More file actions
76 lines (66 loc) · 1.55 KB
/
BlockQueue.h
File metadata and controls
76 lines (66 loc) · 1.55 KB
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
/***************************************************************************************
*
* Copyright (c) 2014 Lejent, Inc. All Rights Reserved
*
**************************************************************************************/
/**
* @file: BlockQueue.h
* @author: zhangxingbiao(xingbiao.zhang@lejent.com)
* @date: 10/28/2016 10:39:19 AM
* @version: 1.0
* @brief:
*
**/
#ifndef __BLOCK_QUEUE_H__
#define __BLOCK_QUEUE_H__
#include <pthread.h>
#include <queue>
template <class EVENT>
class BlockQueue {
public:
BlockQueue(){
pthread_mutex_init(&_mutex, NULL);
pthread_cond_init(&_cond, NULL);
_size = 0;
_free = 0;
}
~BlockQueue(){
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_cond);
}
bool empty(){
return _size == 0 ? true : false;
}
EVENT get() {
pthread_mutex_lock(&_mutex);
_free++;
while(empty()) {
pthread_cond_wait(&_cond, &_mutex);
}
EVENT e = _qu.front();
_qu.pop();
_free--;
_size--;
if(_size > 0 && _free > 0) {
pthread_cond_signal(&_cond);
}
pthread_mutex_unlock(&_mutex);
return e;
}
void put(EVENT e) {
pthread_mutex_lock(&_mutex);
_qu.push(e);
_size++;
if(_free > 0) {
pthread_cond_signal(&_cond);
}
pthread_mutex_unlock(&_mutex);
}
private:
std::queue<EVENT> _qu;
pthread_cond_t _cond;
pthread_mutex_t _mutex;
volatile long _size;
volatile int _free;
};
#endif