-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncBuffer.cpp
More file actions
executable file
·71 lines (60 loc) · 1.5 KB
/
asyncBuffer.cpp
File metadata and controls
executable file
·71 lines (60 loc) · 1.5 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
/*
* AsyncBuffer provides an async buffer to store captured packets
* Last modified for release!
*/
#include <time.h>
#include "common.h"
#include "asyncBuffer.h"
#include "log.h"
extern Log* logger;
/* constructor */
AsyncBuffer::AsyncBuffer()
{
pthread_mutex_init(&access_lock, NULL);
pthread_cond_init(&empty_flag, NULL);
}
/* destructor */
AsyncBuffer::~AsyncBuffer()
{
pthread_cond_broadcast(&empty_flag);
pthread_mutex_unlock(&access_lock);
pthread_mutex_destroy(&access_lock);
pthread_cond_destroy(&empty_flag);
while(!packet_queue.empty())
{
Packet* pkt = packet_queue.front();
packet_queue.pop();
delete pkt;
}
}
/* insert a Packet* into the asyncBuffer */
int AsyncBuffer::push(Packet* pkt)
{
pthread_mutex_lock(&access_lock);
packet_queue.push(pkt);
// notify it is not empty from now on!
pthread_cond_signal(&empty_flag);
pthread_mutex_unlock(&access_lock);
return 0;
}
/* extract a Packet* from the asyncBuffer */
Packet* AsyncBuffer::pop(double timeout)
{
struct timespec to;
clock_gettime(CLOCK_REALTIME, &to);
ts_add(&to, double2ts(timeout)) ;
pthread_mutex_lock(&access_lock);
if (packet_queue.empty())
{
//wait the queue is not empty until timeout
if(pthread_cond_timedwait(&empty_flag, &access_lock, &to)==ETIMEDOUT)
{
pthread_mutex_unlock(&access_lock);
return NULL;
}
}
Packet* pkt = packet_queue.front();
packet_queue.pop();
pthread_mutex_unlock(&access_lock);
return pkt;
}