Skip to content

Instantly share code, notes, and snippets.

@qzchenwl
Last active December 27, 2015 08:49
Show Gist options
  • Save qzchenwl/7298800 to your computer and use it in GitHub Desktop.
Save qzchenwl/7298800 to your computer and use it in GitHub Desktop.
event loop
#pragma once
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
template <typename T>
class BlockingQueue
{
public:
void push(const T& value)
{
{
unique_lock<mutex> lock(mutex_);
queue_.push(value);
}
condition_.notify_one();
}
T pop()
{
unique_lock<mutex> lock(mutex_);
condition_.wait(lock, [&]{ return !queue_.empty(); });
T r(queue_.front());
queue_.pop();
return r;
}
private:
mutex mutex_;
condition_variable condition_;
queue<T> queue_;
};
#include <future>
#include <thread>
#include <chrono>
#include <atomic>
#include <iostream>
#include "BlockingQueue.h"
using namespace std;
class DevMgr;
class IEvent
{
public:
virtual void AsyncExecute(DevMgr *context)
{
printf("AsyncExecute\n");
async(launch::async, [=] {
this_thread::sleep_for(chrono::seconds(1));
this->RealJob(context);
});
}
virtual ~IEvent()
{
printf("IEvent::~IEvent()\n");
}
protected:
virtual void RealJob(DevMgr *context) = 0;
};
class DemoEvent: public IEvent
{
public:
virtual ~DemoEvent()
{
printf("DemoEvent::~DemoEvent()\n");
}
protected:
virtual void RealJob(DevMgr *context)
{
for(int i = 0; i < 10; ++i)
{
printf("do job %d\n", i);
}
}
};
class DevMgr
{
public:
DevMgr()
: end_(false)
, eventQueue_()
{
eventLoop_ = thread(EventLoop, this);
}
~DevMgr()
{
end_ = true;
eventQueue_.push(shared_ptr<IEvent>(new DemoEvent()));
eventLoop_.join();
}
void AddEvent(IEvent *pEvent)
{
eventQueue_.push(shared_ptr<IEvent>(pEvent));
}
private:
static void EventLoop(DevMgr *This)
{
printf("EventLoop 0x%x\n", This);
while(true)
{
if (This->end_) break;
This->eventQueue_.pop()->AsyncExecute(This);
}
}
private:
thread eventLoop_;
BlockingQueue<shared_ptr<IEvent>> eventQueue_;
atomic<bool> end_;
};
int main() {
DevMgr mgr;
mgr.AddEvent(new DemoEvent());
int x; cin >> x;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment