-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathasynwait.cpp
More file actions
75 lines (62 loc) · 1.45 KB
/
asynwait.cpp
File metadata and controls
75 lines (62 loc) · 1.45 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
#include "asynwait.h"
#include <thread>
#include <unistd.h>
AsynWait::AsynWait()
{
}
void AsynWait::start(int precision)
{
if (mStarted == true)
return;
mStarted=true;
mPrecision = precision;
thread thd(&AsynWait::run, this);
mThd.swap(thd);
}
void AsynWait::stop()
{
mStarted=false;
mThd.join();
}
void AsynWait::addWaitPack(IdType packetId, AsynWait::OnWaitTimeout onTimeout, int msTimeo)
{
WaitPack pack;
pack.id = packetId;
pack.handler = onTimeout;
pack.timeo = time_point_cast<milliseconds>(system_clock::now()) + milliseconds(msTimeo);
mPacksMutex.lock();
mWaitPacks.push_back(pack);
mPacksMutex.unlock();
}
void AsynWait::clearWaitPack(IdType packetId)
{
mPacksMutex.lock();
mWaitPacks.remove_if([packetId](WaitPack pack){
return pack.id = packetId;
});
mPacksMutex.unlock();
}
void AsynWait::run()
{
list<WaitPack> timeos;
while (mStarted) {
usleep(mPrecision*1000);
timeos.clear();
auto cur = system_clock::now();
mPacksMutex.lock();
mWaitPacks.remove_if([&cur, &timeos](const WaitPack& pack){
if (cur > pack.timeo)
{
timeos.push_back(pack);
return true;
}
return false;
});
mPacksMutex.unlock();
if (!timeos.empty())
{
for (auto& pack : timeos)
pack.handler(pack.id);
}
}
}