qthread的run方法
一个qthread对象管理一个线程,一般从qthread继承一个自定义的类,并实现run方法,在run函数中实现线程需要完成的任务。qthread自身定义了started() 和finish()两个信号,started() 信号是在开始执行之前发射,finished()信号是在线程就要结束时发射。
class workerthread : public qthread { q_object void run() override { // todo emit sigmsg(result); } signals: void sigmsg(const qstring &s); }; void main() { workerthread *workerthread = new workerthread(this); workerthread->start(); }
特点
1、优点:可以通过信号槽与外界进行通信。
2、缺点:每次新建一个线程都需要继承qthread,实现一个新类,使用不太方便。
要自己进行资源管理,线程释放和删除。并且频繁的创建和释放会带来比较大的内存开销。
3、适用场景:qthread适用于那些常驻内存的任务。
qobject的movetothread
创建一个继承qobject的类mythread,把要执行的计算放到一个函数中dowork,然后new一个qthread,并把创建的mythread类movetothread到创建好的子线程中,然后start子线程,这样就实现了一个子线程。这里一定要通过信号去调用dowork函数。
class mythread:public qobject { q_object public slots: void dowork(){ int i=0; while(i<4){ // todo qdebug()<<qthread::currentthread()<<" "<<i++; } } }; class mytest :public qobject { q_object qthread workerthread; public: mytest(){ mythread* mythread = new mythread(); // 这个任务函数不能有父对象,有父对象时不可以movetothread mythread->movetothread(&workerthread); workerthread.start(); connect(this,&mytest::active,mythread,&mythread::dowork); // 一定要通过槽函数去调用对应的函数,否则还是在主线程 } ~mytest(){ workerthread.quit(); } signals: void active(); }; mainwindow::mainwindow(qwidget *parent) : qmainwindow(parent) , ui(new ui::mainwindow) { qdebug()<<qthread::currentthread(); ui->setupui(this); mytest* t = new mytest(); t->active(); qthread::sleep(3000); t->deletelater(); }
特点
一定要通过槽函数的形式去调用函数,要注意!你创建的qthread对象实例,仍然存活在主线程上,而非子线程。所以如果你直接调用其中的函数,那么还是在主线程上运行的。该方法并不是线程安全的。
qrunnalble的run
继承qrunnable,并重写run虚函数,使用qthreadpool启动线程
class runnable:public qrunnable { public: runnable(); ~runnable(); void run(); }; runnable::runnable():qrunnable() { } runnable::~runnable() { cout<<"~runnable()"<<endl; } void runnable::run() { cout<<"runnable::run()thread :"<<qthread::currentthreadid()<<endl; cout<<"dosomething ...."<<endl; } int main(int argc, char *argv[]) { qcoreapplication a(argc, argv); cout<<"mainthread :"<<qthread::currentthreadid()<<endl; runnable runobj; qthreadpool::globalinstance()->start(&runobj); returna.exec(); }
特点
1,无需手动释放资源,qthreadpool启动线程执行完成后会自动释放。
2,不能使用信号槽与外界通信。
3,qrunnable适用于线程任务量比较大,需要频繁创建线程。qrunnable能有效减少内存开销。
qtconcurrent的run
使用qtconcurrent编写的程序会根据可用的处理器内核数自动调整使用的线程数。qtconcurrent::run能够方便快捷的将任务丢到子线程中去执行,无需继承任何类,也不需要重写函数,使用非常简单。通过qtconcurrent::run()返回的qfuture不支持取消、暂停,返回的qfuture只能用于查询函数的运行/完成状态和返回值。
函数原型:
qfuture<t> qtconcurrent::run(function function, ...) qfuture<t> qtconcurrent::run(qthreadpool *pool, function function, ...)
使用方式
qtconcurrent::run([=]() { // todo });
线程同步
基于qmutex互斥同步
qmutex的目的是保护一个对象、数据结构或者代码段,所以同一时间只有一个线程可以访问它。如果使用mutex锁那么多个线程在访问一段代码的时候是存在阻塞的,一个执行完毕下一个线程才会继续执行
lock():试图锁定互斥量。如果另一个线程已经锁定这个互斥量,那么这次调用将阻塞直到那个线程把它解锁。
unlock():进行解锁
trylock():试图锁定互斥量。如果锁被得到,这个函数返回真。如果另一个进程已经锁定了这个互斥量,这个函数返回假,而不是一直等到这个锁可用为止
qmutex mutex; void debuginfo() { mutex.lock(); qdebug("abc"); qdebug("def"); mutex.unlock(); }
基于qreadwritelock的线程同步
一种读写锁,用于保护可以进行读写访问的资源。这种索允许多个线程同时进行只读访问,但是一旦一个线程想要写入资源,则必须阻止所有其他线程,直到写入完成。
qreadwritelock lock; void readerthread::run() { ... lock.lockforread(); read_file(); lock.unlock(); ... } void writerthread::run() { ... lock.lockforwrite(); write_file(); lock.unlock(); ... }
void lockforread():锁定读取锁。如果另一个线程已锁定以进行写入,则此函数将阻塞当前线程。如果线程已经锁定写入,则无法锁定读取。void lockforwrite():锁定写入锁。如果另一个线程(包括当前线程)已锁定读取或写入,则此函数将阻塞当前线程。如果线程已经为读取而锁定,则不会为写入而锁定。
基于qwaitcondition的线程同步
qwaitcondition 允许线程在某些情况发生时唤醒另外的线程。一个或多个线程可以阻塞等待一qwaitcondition ,用wakeone()或wakeall()设置一个条件。wakeone()随机唤醒一个,wakeall()唤醒所有
const int datasize = 100000; const int buffersize = 8192; char buffer[buffersize]; qwaitcondition buffernotempty; qwaitcondition buffernotfull; qmutex mutex; int numusedbytes = 0; class producer : public qthread { public: void run(); }; void producer::run() { qsrand(qtime(0,0,0).secsto(qtime::currenttime())); for (int i = 0; i < datasize; ++i) { mutex.lock(); if (numusedbytes == buffersize) buffernotfull.wait(&mutex); mutex.unlock(); buffer[i % buffersize] = "acgt"[(int)qrand() % 4]; mutex.lock(); ++numusedbytes; buffernotempty.wakeall(); mutex.unlock(); } } class consumer : public qthread { public: void run(); }; void consumer::run() { for (int i = 0; i < datasize; ++i) { mutex.lock(); if (numusedbytes == 0) buffernotempty.wait(&mutex); mutex.unlock(); fprintf(stderr, "%c", buffer[i % buffersize]); mutex.lock(); --numusedbytes; buffernotfull.wakeall(); mutex.unlock(); } fprintf(stderr, "\n"); } int main(int argc, char *argv[]) { qcoreapplication app(argc, argv); producer producer; consumer consumer; producer.start(); consumer.start(); producer.wait(); consumer.wait(); return 0; }
到此这篇关于一文带你了解qt多线程的实现方式的文章就介绍到这了,更多相关qt多线程内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论