-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateContext.cpp
59 lines (45 loc) · 1.25 KB
/
StateContext.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
/*
* StateContext.cpp
*
* Created on: Jan 31, 2013
* Author: dam7633
*/
#include "StateContext.h"
#include <pthread.h>
#include "EventCenter.h"
StateContext::StateContext() {
// Register the context with the event center.
EventCenter::DefaultEventCenter()->registerContext(this);
// Start the run loop of the context.
start();
}
void StateContext::accept(Event event) {
pthread_sleepon_lock();
// Push the event into the state context's queue.
eventQueue.push(event);
// Signal that we can process an event from the queue.
pthread_sleepon_signal(&eventQueue);
pthread_sleepon_unlock();
}
void StateContext::handle(Event event) {
childState->accept(event);
}
void* StateContext::run() {
// Continuously pop events off our queue and accept them.
while (!killThread) {
pthread_sleepon_lock();
// This thread should sleep until there is an event.
while (eventQueue.empty()) {
pthread_sleepon_wait(&eventQueue);
}
// Dequeue the next event and accept it.
Event event = eventQueue.front();
eventQueue.pop();
this->handle(event);
pthread_sleepon_unlock();
}
return NULL;
}
StateContext* StateContext::getStateContext() {
return this;
}