C++ - Simple thread example of a string message processor
less than 1 minute read
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
class StringMessageProcessor
{
public :
StringMessageProcessor ()
{
m _ exit = false ;
m _ messageArrived = false ;
}
~ StringMessageProcessor ()
{
m _ thread . join () ;
}
void SetHandler ( std ::function < void ( std ::string const & ) > msgHandler )
{
std ::unique _ lock < std ::mutex > lock ( m _ condvarMutex ) ;
m _ msgHandler = msgHandler ;
}
void Start ()
{
boost ::thread thread ([ this ] {
while ( ! m _ exit )
{
std ::unique _ lock < std ::mutex > lock ( m _ condvarMutex ) ;
m _ condvar . wait ( lock , [ this ] { return m _ exit || m _ messageArrived ; }) ;
if ( ! m _ exit )
{
std ::vector < Item > data ;
auto queueSize = m _ msgQueue . size () ;
while ( m _ msgQueue . size () > 0 ) {
data . push _ back ( m _ msgQueue . front ()) ;
m _ msgQueue . pop () ;
}
lock . unlock () ;
for ( auto const & msg : data ) {
m _ processor -> processItem ( msg , queueSize ) ;
}
}
}
}) ;
m _ thread . swap ( thread ) ;
}
void Stop ()
{
{
std ::lock _ guard < std ::mutex > lk ( m _ condvarMutex ) ;
m _ exit = true ;
}
m _ condvar . notify _ all () ;
}
bool PushMessage ( std ::string const & msg )
{
std ::lock _ guard < std ::mutex > lk ( m _ condvarMutex ) ;
m _ msgQueue . push ( msg ) ;
m _ messageArrived = true ;
m _ condvar . notify _ one () ;
return true ;
}
private :
boost ::thread m _ thread ;
std ::mutex m _ condvarMutex ;
std ::condition _ variable m _ condvar ;
bool m _ exit ;
bool m _ messageArrived ;
std ::queue < std ::string > m _ msgQueue ;
std ::function < void ( std ::string const & ) > m _ msgHandler ;
} ;