当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
1 Star 0 Fork 41

Bemied/QEvent
暂停

forked from 启家/QEvent
暂停
 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
QJEventLoop.h 2.29 KB
一键复制 编辑 原始数据 按行查看 历史
qijia 提交于 2017-06-23 07:15 . 【fecture】使用模板多参数重构
#pragma once
#include <memory>
#include <list>
#include <thread>
#include "QJMutex.h"
namespace qijia
{
struct IDataBase
{
virtual ~IDataBase() {}
virtual void run() = 0;
};
template <typename FunCall>
struct CDataBase : public IDataBase
{
CDataBase(FunCall&& f)
: m_fun(std::forward<FunCall>(f))
{}
void run()
{
m_fun();
}
FunCall m_fun;
};
class QJEventData
{
public:
template <typename FunCall, typename ... Args>
QJEventData(FunCall&& f, Args&& ... args)
{
m_pFun = makeCDataBase(std::bind(std::forward<FunCall>(f), std::forward<Args>(args)...));
}
void run()
{
m_pFun->run();
}
private:
template <typename FunCall>
std::shared_ptr<CDataBase<FunCall>> makeCDataBase(FunCall&& f)
{
return std::make_shared<CDataBase<FunCall>>(std::forward<FunCall>(f));
}
std::shared_ptr<IDataBase> m_pFun;
};
// this loop for other thread sendevent to main thread
class QJEventLoop
{
typedef std::list<std::shared_ptr<QJEventData>> eventDataList;
typedef std::shared_ptr<eventDataList> eventDataListPtr;
public:
void init()
{
m_mainId = (std::this_thread::get_id ());
}
bool loop()
{
if ( std::this_thread::get_id () != m_mainId)
{
//error not run in main thread
return false;
}
eventDataListPtr eventList;
{
qijia::QJMutex lock (mtx);
eventList.reset (new eventDataList(*m_eventList));
m_eventList->clear();
}
auto iter = eventList->begin();
while(iter != eventList->end())
{
(*iter)->run();
iter++;
}
return true;
}
static QJEventLoop& App()
{
static QJEventLoop instance;
return instance;
}
void addEventList(std::shared_ptr<QJEventData> event)
{
qijia::QJMutex lock (mtx);
if (!m_eventList.unique ())
{
m_eventList.reset (new eventDataList(*m_eventList));
}
m_eventList->push_back(event);
}
private:
QJEventLoop()
:m_mainId(std::this_thread::get_id ())
{
m_eventList.reset(new eventDataList);
}
std::thread::id m_mainId;
eventDataListPtr m_eventList;
std::mutex mtx;
};
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/Bemied/QEvent.git
git@gitee.com:Bemied/QEvent.git
Bemied
QEvent
QEvent
master

搜索帮助