Qt 執行緒建立的兩種方式

2021-08-26 11:58:09 字數 638 閱讀 8417

1.定義繼承qthread的類a 複寫run()函式;

2.在主線程中例項化a物件a

3.通過呼叫a->start()啟動執行緒,執行緒會自動呼叫run()虛函式;run不可直接呼叫;

#ifndef mythread_h

#define mythread_h

#include class mythread: public qthread

;#endif // mythread_h

#include "mythread.h"

#include mythread::mythread()

void mythread::run()

int main(int argc, char *argv)

2.在主線程中例項化a物件a,再例項化qthread類物件b

3.通過a.movetothread(&b);將a物件的實現移入執行緒b物件作用範圍內執行

4.b->start()啟動執行緒;

5.通過訊號與槽的方式啟動呼叫a類成員函式;

// worker 類定義 cpp

#include

class worker : public qobject  

Qt建立執行緒兩種方式的區別

使用qt建立執行緒有兩種方式,方式a使用movetothread,方式b是直接繼承qthread。差異主要在於方式a的槽函式將會在新執行緒中執行,而方式b的槽函式在舊執行緒中執行。結論如下 ps 舊執行緒在這裡指主線程,而新執行緒指qthread建立出的執行緒。相同點 不同點 綜上 使用方式b是需要...

執行緒建立的兩種方式

建立執行緒的兩種方式 1.繼承thread並重寫方法,在run方法中定義執行緒要執行的任務 class mythread extends thread public class threaddemo1 2.實現runable介面並重寫run方法 class myrunnable implements...

建立執行緒的兩種方式

thread thread new thread catch interruptedexception e system.out.println thread.currentthread getname system.out.println this.getname thread.start thr...