Created
November 27, 2013 12:33
-
-
Save AlexKordic/7674932 to your computer and use it in GitHub Desktop.
Event dispatch in C++ (Observer) for Sima. Kole asked for Threading bits.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <Windows.h> | |
#include <process.h> | |
class IncrementInterface { | |
public: | |
virtual int increment(int amount) = 0; | |
}; | |
class SimpleClass : public IncrementInterface | |
{ | |
public: | |
int _value; | |
int _id; | |
SimpleClass(int initial_value, int id) : _value(initial_value), _id(id) {} | |
// A method yielding result depending on internal state | |
int increment(int amount) { | |
_value += amount; | |
printf(" increment event received id=%d val=%d \n", _id, _value); | |
return _value; | |
} | |
typedef int (SimpleClass:: * IncrementMethodType) (int initial_value); | |
}; | |
#include <deque> | |
struct Params { | |
Calculator * _our_calc; | |
}; | |
/// | |
/// | |
/// Threading used for events | |
/// | |
/// | |
class Calculator { | |
public: | |
// | |
// Events logic: | |
// | |
std::deque<IncrementInterface *> _registered; | |
void register_for_event(IncrementInterface * subject) { | |
_registered.push_back(subject); | |
} | |
void incremented_event(int amount) { | |
for (std::deque<IncrementInterface *>::iterator it = _registered.begin(); it!=_registered.end(); ++it) { | |
(*it)->increment(amount); | |
} | |
} | |
// | |
// Threading logic: | |
// | |
uintptr_t _thread; | |
Calculator() : _thread(0) {} | |
void start() { | |
Params * params = new Params; | |
params->_our_calc = this; | |
_thread = _beginthread(__run_in_thread, 60000, params); | |
} | |
static void __run_in_thread(void * a) { | |
Params * p = (Params *) a; | |
p->_our_calc->run(); | |
delete p; | |
} | |
// invoking events | |
void run() { | |
incremented_event(3); | |
incremented_event(4); | |
incremented_event(5); | |
} | |
void wait() { | |
DWORD result = WaitForSingleObject( (HANDLE) _thread, INFINITE ); | |
} | |
}; | |
int main() { | |
SimpleClass obj(7, 1), obj2(5, 2); | |
// | |
// Using method pointers - dirty | |
// | |
int (SimpleClass:: * inc_pointer)(int) = &SimpleClass::increment; | |
SimpleClass * _this = &obj; | |
// call inc_pointer with this set to _this | |
printf(" result: %d \n", (*_this.*inc_pointer)(3)); | |
printf(" result: %d \n", (_this->*inc_pointer)(4)); | |
printf(" result: %d \n", (*_this.*inc_pointer)(5)); | |
Calculator calc; | |
calc.register_for_event(&obj); | |
calc.register_for_event(&obj2); | |
calc.start(); | |
calc.wait(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment