-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbasic_queue.h
More file actions
78 lines (63 loc) · 1.38 KB
/
basic_queue.h
File metadata and controls
78 lines (63 loc) · 1.38 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
#ifndef __BASIC_QUEUE__
#define __BASIC_QUEUE__
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include "list.h"
template<typename T>
class BasicQueue
{
public:
BasicQueue(int capacity)
{
this->res_max = capacity;
this->res_cnt = 0;
this->put_wait_cnt = 0;
}
void enqueue(T element)
{
pthread_mutex_lock(&this->mutex);
while (this->res_cnt >= this->res_max)
{
this->put_wait_cnt++;
pthread_cond_wait(&this->put_cond, &this->mutex);
this->put_wait_cnt--;
}
this->res_list.add_tail(element);
this->res_cnt++;
// if (this->res_cnt == 1)
pthread_cond_signal(&this->get_cond);
pthread_mutex_unlock(&this->mutex);
}
T dequeue()
{
T ret;
pthread_mutex_lock(&this->mutex);
while (this->res_cnt == 0)// && this->res_list.empty())
pthread_cond_wait(&this->get_cond, &this->mutex);
if (this->res_cnt != 0)
{
this->res_list.get_head(ret);
this->res_cnt--;
// if (this->put_wait_cnt > 0)
pthread_cond_signal(&this->put_cond);
}
pthread_mutex_unlock(&this->mutex);
// pthread_cond_signal(&this->put_cond);
return ret;
}
int size()
{
return this->res_cnt;
}
private:
int res_max;
int res_cnt;
int put_wait_cnt;
List<T> res_list;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t put_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t get_cond = PTHREAD_COND_INITIALIZER;
};
#endif