-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSelectableQueue.h
108 lines (98 loc) · 2.28 KB
/
SelectableQueue.h
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
/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#ifndef UTIL_QUEUE_H
#define UTIL_QUEUE_H
#include <unistd.h>
#include <pthread.h>
#include <queue>
// Selectable queue, multi writers, single reader
template <class T>
class SelectableQueue {
private:
int fds[2];
pthread_mutex_t mutex;
std::queue<T> items;
public:
SelectableQueue();
~SelectableQueue();
int fd() {
return fds[0];
}
int size();
// multi writer
int push(const T item);
// single reader
int pop(T* data);
};
template <class T>
SelectableQueue<T>::SelectableQueue() {
if (pipe(fds) == -1) {
fprintf(stderr, "create pipe error\n");
exit(0);
}
pthread_mutex_init(&mutex, NULL);
}
template <class T>
SelectableQueue<T>::~SelectableQueue() {
pthread_mutex_destroy(&mutex);
close(fds[0]);
close(fds[1]);
}
template <class T>
int SelectableQueue<T>::push(const T item) {
if (pthread_mutex_lock(&mutex) != 0) {
return -1;
}
{ items.push(item); }
if (::write(fds[1], "1", 1) == -1) {
fprintf(stderr, "write fds error\n");
exit(0);
}
pthread_mutex_unlock(&mutex);
return 1;
}
template <class T>
int SelectableQueue<T>::size() {
int ret = 0;
pthread_mutex_lock(&mutex);
ret = items.size();
pthread_mutex_unlock(&mutex);
return ret;
}
template <class T>
int SelectableQueue<T>::pop(T* data) {
int n, ret = 1;
char buf[1];
while (1) {
n = ::read(fds[0], buf, 1);
if (n < 0) {
if (errno == EINTR) {
continue;
} else {
return -1;
}
} else if (n == 0) {
ret = -1;
} else {
if (pthread_mutex_lock(&mutex) != 0) {
return -1;
}
{
if (items.empty()) {
fprintf(stderr, "%s %d error!\n", __FILE__, __LINE__);
pthread_mutex_unlock(&mutex);
return -1;
}
*data = items.front();
items.pop();
}
pthread_mutex_unlock(&mutex);
}
break;
}
return ret;
}
#endif