forked from G4GUO/express_server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffers.cpp
88 lines (85 loc) · 1.55 KB
/
buffers.cpp
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
#include <queue>
#include <deque>
#include <list>
#include <queue>
#include <semaphore.h>
#include <pthread.h>
#include <malloc.h>
#include "express_server.h"
using namespace std;
// tx buffer queue
static queue <uchar *> m_tx_q;
// spare buffer pool
static queue <uchar *> m_po_q;
// Mutexes
static pthread_mutex_t mutex_po;
static pthread_mutex_t mutex_tx;
//
// Allocate a new buffer
//
uchar *alloc_buff(void)
{
uchar *b;
pthread_mutex_lock( &mutex_po );
if(m_po_q.size() > 0 )
{
b = m_po_q.front();
m_po_q.pop();
}
else
{
// No available memory so allocate some
b = (uchar *)malloc(TP_SIZE);
}
pthread_mutex_unlock( &mutex_po );
return b;
}
//
// Release a buffer
//
void rel_buff(uchar *b)
{
pthread_mutex_lock( &mutex_po );
m_po_q.push(b);
pthread_mutex_unlock( &mutex_po );
}
//
// Post a buffer to the tx queue
//
void post_buff( uchar *b)
{
pthread_mutex_lock( &mutex_tx );
if(m_tx_q.size() < MAX_Q_LEN)
m_tx_q.push(b);
else
rel_buff(b);// Queue overflow
pthread_mutex_unlock( &mutex_tx );
}
//
// Get a buffer from the tx queue
//
uchar *get_buff(void)
{
uchar *b;
pthread_mutex_lock( &mutex_tx );
if(m_tx_q.size() > 0 )
{
b = m_tx_q.front();
m_tx_q.pop();
}
else
{
b = NULL;
}
pthread_mutex_unlock( &mutex_tx );
return b;
}
//
// Initialise the buffers
//
void buf_init(void)
{
// Create the mutex
pthread_mutex_init( &mutex_tx, NULL );
pthread_mutex_init( &mutex_po, NULL );
}