#pragma once
#include <qthread.h>
#include <functional>
class QIoService : QObject
{
public:
QIoService(bool startinthread)
{
if(startinthread)
{
worker=new QThread(NULL);
worker->start();
this->moveToThread(worker);
}
else
{
//this object is created in create thread!!!
}
}
void post(std::function<void()> func);
void send(std::function<void()> func);
void post(std::function<void()> func,int ms);
void send(std::function<void()> func,int ms);
virtual bool event ( QEvent * e);
protected:
QThread *worker;
};
//this should run in mainthread
extern QIoService *main_ioservice;
#include "stdafx.h"
#include "qioservice.h"
#include <qapplication.h>
#include <qtconcurrentrun.h>
QIoService *main_ioservice=NULL;
class FunctionEvent : public QEvent
{
public:
static const QEvent::Type myType = static_cast<QEvent::Type>(2000);
FunctionEvent(std::function<void()> f)
:QEvent(myType)
{
func=f;
}
~FunctionEvent()
{
//这个他会自动删除
}
std::function<void()> func;
};
void QIoService::post(std::function<void()> func)
{
QApplication::instance()->postEvent(this,new FunctionEvent(func));
}
void QIoService::send(std::function<void()> func)
{
QApplication::instance()->sendEvent(this,new FunctionEvent(func));
}
void QIoService::post(std::function<void()> func,int ms)
{
auto lam = [&]()
{
QThread::currentThread()->wait(ms);
post(func);
};
QtConcurrent::run(lam);
}
void QIoService::send(std::function<void()> func,int ms)
{
auto lam = [&]()
{
QThread::currentThread()->wait(ms);
send(func);
};
QtConcurrent::run(lam);
}
bool QIoService::event ( QEvent * e)
{
if(e->type()==FunctionEvent::myType)
{
FunctionEvent *fe=(FunctionEvent *)e;
fe->func();
return true;
//这个他会自动删除,不用我们自己手工delete
}
return false;
}