查看完整版本: [-- 秀一个自己写的小类,主要用于跨线程调用。欢迎指正 --]

QTCN开发网 -> Qt代码秀 -> 秀一个自己写的小类,主要用于跨线程调用。欢迎指正 [打印本页] 登录 -> 注册 -> 回复主题 -> 发表主题

sevencat 2016-01-08 14:06

秀一个自己写的小类,主要用于跨线程调用。欢迎指正

#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;
}

stlcours 2016-02-01 17:05
看不懂,能解释一下吗?

z609932088 2016-02-01 17:18
我是看图的呃

更好 2016-02-02 22:42
代码都往this发送事件,实际使用时是否需要把this改成接受的指针?


sevencat 2016-02-19 19:35
比如你在另外一个线程,你收到数据,想修改界面。就弄个全局变量
QIoService g_ui_ios(false);
你只要
g_ui_ios.send([你的变量]
{
  修改界面数据,这个会在主线程执行
});

如果你是想写个任务队列,
QIoService g_worker_ios(true);
你要把某段事情丢到其他线程执行,就
g_worker_ios.send([]
{
  这段会在其他线程执行。
  如果执行完了,又想在主线程执行某段,这里可以继续
  g_ui_ios.send([]
  {
    这段会在主线程执行
  });
});

sichuanwww 2016-06-26 12:18

哥依然潇洒 2016-10-10 14:42
哥哥。这个能不能给个简单的例子啊,我想实现主线程显示界面,子线程用于数据库操作,以防界面弹出卡顿 感谢!!!


查看完整版本: [-- 秀一个自己写的小类,主要用于跨线程调用。欢迎指正 --] [-- top --]



Powered by phpwind v8.7 Code ©2003-2011 phpwind
Gzip disabled