simulate events
windows system maintains a msg queue, and any process that supports msg will create an thread that have a loop which checks its own msg queue;
we can set a callback for it through define an event.
// file Eventt.h
#include <map> #include <functional> using namespace std; template<class T1, class T2> class Eventt { public: typedef void FunctionA(T1, T2); Eventt() :eventID(0), softwareID(0){} template<class T3> int addHandler(T3 t3) { m_handlers.emplace(eventID, t3); return eventID++; } void operator()(T1 t1, T2 t2) { for (auto i : m_handlers) i.second(t1, t2); } private: map<int, function<FunctionA> > m_handlers; int eventID; int softwareID; };
#include "Eventt.h" #include <iostream> #include <queue> #include <thread> #include <stdlib.h> #include <windows.h> using namespace std; // to simulate msg and event machinism used in Windows struct Messg { enum SoftType{ NUL, A, B }; int a, b, Type; Messg(int aa, int bb, int cc) :a(aa), b(bb), Type(cc){} }; struct { queue<pair<int, int>> m_softA, m_softB; queue<Messg> m_system; } Computr; void fuctionA(int a, int b) { cout << "software A : " << a*b << endl; } void fuctionB(int a, int b) { cout << "software B : " << a * b <<"\t\t" << a+b << endl; } void FunctionCC(void) { int a, b, c; while (1) { Sleep(1500); a = rand() % 100; b = rand() % 100; c = rand() % 3; Computr.m_system.push(Messg(a, b, c)); } } void FunctionAA(void) { Eventt<int, int> ea;
// register callback ea.addHandler(fuctionA); while (1) { Sleep(1000); while (!Computr.m_softA.empty()) { pair<int, int> msg(Computr.m_softA.front()); ea(msg.first, msg.second); Computr.m_softA.pop(); } } } void FunctionBB(void) { Eventt<int, int> ea; ea.addHandler(fuctionB); while (1) { Sleep(1000); while (!Computr.m_softB.empty()) { pair<int, int> msg(Computr.m_softB.front()); ea(msg.first, msg.second); Computr.m_softB.pop(); } } } int main() // the function main is like a system { thread softA(FunctionAA), softB(FunctionBB), softC(FunctionCC); while (1) { Sleep(700); if (!Computr.m_system.empty()) { Messg temp = Computr.m_system.front(); pair<int, int> tempmsg(temp.a, temp.b); switch (temp.Type) { case Messg::NUL:Computr.m_softA.push(tempmsg); Computr.m_softB.push(tempmsg); break; case Messg::A:Computr.m_softA.push(tempmsg); // send mesg to softA break; case Messg::B:Computr.m_softB.push(tempmsg); // send mesg to softB break; default: ; } Computr.m_system.pop(); } } }