-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdouble_list_queue.h
More file actions
97 lines (70 loc) · 1.72 KB
/
Copy pathdouble_list_queue.h
File metadata and controls
97 lines (70 loc) · 1.72 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#ifndef __DOUBLE_LIST_QUEUE__
#define __DOUBLE_LIST_QUEUE__
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include "list.h"
template<typename T>
class DoubleListQueue
{
public:
DoubleListQueue(int capacity)
{
this->res_max = capacity;
this->put_res_cnt = 0;
this->get_res_cnt = 0;
}
void enqueue(T element)
{
pthread_mutex_lock(&this->put_mutex);
while (this->put_res_cnt >= this->res_max)
pthread_cond_wait(&this->put_cond, &this->put_mutex);
this->put_list.add_tail(element);
this->put_res_cnt++;
pthread_mutex_unlock(&this->put_mutex);
pthread_cond_signal(&this->get_cond);
}
T dequeue()
{
T ret;
pthread_mutex_lock(&this->get_mutex);
if (!this->get_list.empty() || this->swap_list() > 0)
{
this->get_list.get_head(ret);
this->get_res_cnt--;
// } else {
}
pthread_mutex_unlock(&this->get_mutex);
return ret;
}
int swap_list()
{
pthread_mutex_lock(&this->put_mutex);
while (this->put_res_cnt == 0)
pthread_cond_wait(&this->get_cond, &this->put_mutex);
this->get_res_cnt = this->put_res_cnt;
if (this->get_res_cnt > this->res_max - 1)
pthread_cond_broadcast(&this->put_cond);
this->get_list = std::move(this->put_list);
this->put_res_cnt = 0;
pthread_mutex_unlock(&this->put_mutex);
return this->get_res_cnt;
}
int size()
{
return this->put_res_cnt + this->get_res_cnt;
}
private:
int res_max;
List<T> put_list;
List<T> get_list;
int put_res_cnt;
int get_res_cnt;
pthread_mutex_t put_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t get_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t put_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t get_cond = PTHREAD_COND_INITIALIZER;
};
#endif