1. 程式人生 > >QT基於UDP通訊的多執行緒程式設計問題

QT基於UDP通訊的多執行緒程式設計問題

近來用Qt編寫一段多執行緒的TcpSocket通訊程式,被其中Qt中報的幾個warning搞暈了,一會兒是說“Cannot create children for a parent that is in a different thread”,有時候又是“QSocketNotifier: socket notifiers cannot be enabled from another thread”,還經常又Assert failure:Cannot send events toobjects owned by a different thread,從而導致程式崩潰。

為徹底搞清原因並解決問題,在查閱大量資料和Qt文件之後,理清了其中的機制,也對多執行緒程式設計中的QObject物件建立以及connect執行有更清楚的認識:

1. 一個物件的執行緒就是建立該物件時的執行緒,而不論該物件的定義是儲存在那個執行緒中;

2. QObject的connect函式有幾種連線方式,

a) DirectConnection,訊號傳送後槽函式立即執行,由sender的所線上程執行;

b) QueuedConnection,訊號傳送後返回,相關槽函式由receiver所在的執行緒在返回到事件迴圈後執行;

c) 預設使用的是Qt::AutoConnection,當sender和receiver在同一個執行緒內時,採用DirectConnection的方式,當sender和receiver在不同的執行緒時,採用QueuedConnection的方式。

為了更清楚的理解這些問題,在此特編了個小例子說明一下。首先定義一個從QObject繼承的類SomeObject,包含一個訊號someSignal和一個成員函式callEmitSignal,此函式用於傳送前面的someSignal訊號。定義如下:

// define Object class

  1. class SomeObject : public QObject  
  2. {  
  3.     Q_OBJECT  
  4. public:  
  5.     SomeObject(QObject* parent=0) : QObject(parent) {}  
  6. void callEmitSignal()  // 用於傳送訊號的函式
  7.     {  
  8.         emit someSignal();  
  9.     }  
  10. signals:  
  11. void someSignal();  
  12. };

然後再定義一個從QThread繼承的執行緒類SubThread,它包含一個SomeObject的物件指標obj,另外有一個slot函式someSolt,定義如下:

  1. class SubThread : public QThread  
  2. {  
  3.     Q_OBJECT  
  4. public:  
  5.     SubThread(QObject* parent=0) : QThread(parent){}  
  6. virtual ~SubThread()  
  7.     {  
  8. if (obj!=NULL) delete obj;  
  9.     }  
  10. public slots:  
  11. // slot function connected to obj's someSignal
  12. void someSlot();  
  13. public:  
  14.     SomeObject * obj;  
  15. };  
  16. // slot function connected to obj's someSignal
  17. void SubThread::someSlot()  
  18. {  
  19.     QString msg;  
  20.     msg.append(this->metaObject()->className());  
  21.     msg.append("::obj's thread is ");  
  22. if (obj->thread() == qApp->thread())  
  23.     {  
  24.         msg.append("MAIN thread;");  
  25.     }  
  26. elseif (obj->thread() == this)  
  27.     {  
  28.         msg.append("SUB thread;");  
  29.     }  
  30. else
  31.     {  
  32.         msg.append("OTHER thread;");  
  33.     }  
  34.     msg.append(" someSlot executed in ");  
  35. if (QThread::currentThread() == qApp->thread())  
  36.     {  
  37.         msg.append("MAIN thread;");  
  38.     }  
  39. elseif (QThread::currentThread() == this)  
  40.     {  
  41.         msg.append("SUB thread;");  
  42.     }  
  43. else
  44.     {  
  45.         msg.append("OTHER thread;");  
  46.     }  
  47.     qDebug() << msg;  
  48.     quit();  
  49. }

這裡someSlot函式主要輸出了obj所在的執行緒和slot函式執行執行緒。

接著從SubThread又繼承了3個執行緒類,分別是SubThread1, SubThread2, SubThread3.分別實現執行緒的run函式。定義如下:

  1. // define sub thread class 1
  2. class SubThread1 : public SubThread  
  3. {  
  4.     Q_OBJECT  
  5. public:  
  6.     SubThread1(QObject* parent=0);  
  7. // reimplement run
  8. void run();  
  9. };  
  10. class SubThread2 : public SubThread  
  11. {  
  12.     Q_OBJECT  
  13. public:  
  14.     SubThread2(QObject* parent=0);  
  15. // reimplement run
  16. void run();  
  17. };  
  18. class SubThread3 : public SubThread  
  19. {  
  20.     Q_OBJECT  
  21. public:  
  22.     SubThread3(QObject* parent=0);  
  23. // reimplement run
  24. void run();  
  25. };

在主程式中分別建立3個不同的執行緒並執行,檢視執行結果。

  1. int main(int argc, char *argv[])  
  2. {  
  3.     QCoreApplication a(argc, argv);  
  4.     SubThread1* t1 = new SubThread1(&a); //由主執行緒建立
  5.     t1->start();  
  6.     SubThread2* t2 = new SubThread2(&a); //由主執行緒建立
  7.     t2->start();  
  8.     SubThread3* t3 = new SubThread3(&a); //由主執行緒建立
  9.     t3->start();  
  10. return a.exec();  
  11. }

下面我們來分析不同寫法的程式,其obj物件所在的執行緒空間和someSlot函式執行的執行緒空間分別是怎樣的。

首先看SubThread1的實現:

  1. ////////////////////////////////////////////////////////
  2. // class SubThread1
  3. ////////////////////////////////////////////////////////
  4. SubThread1::SubThread1(QObject* parent)  
  5.     : SubThread(parent)  
  6. {  
  7.     obj = new SomeObject();//由主執行緒建立
  8.     connect(obj, SIGNAL(someSignal()), this, SLOT(someSlot()));  
  9. }  
  10. // reimplement run
  11. void SubThread1::run()  
  12. {  
  13.     obj->callEmitSignal();  
  14.     exec();  
  15. }

可以看到,obj是在建構函式中被建立的,那麼建立obj物件的執行緒也就是建立SubThread1的執行緒,一般是主執行緒,而不是SubThread1所代表的執行緒。同時由於obj和this(即t1)都位於主執行緒,所以someSlot函式也是由主執行緒來執行的。

而線上程SubThread2中,我們把obj物件的建立放到子執行緒的run函式中,那麼obj物件的執行緒就應該SubThread2代表的執行緒,即t2,就不再是主執行緒了。

  1. ////////////////////////////////////////////////////////
  2. // class SubThread2
  3. ////////////////////////////////////////////////////////
  4. SubThread2::SubThread2(QObject* parent)  
  5.     : SubThread(parent)  
  6. {  
  7.     obj=0;  
  8. }  
  9. // reimplement run
  10. void SubThread2::run()  
  11. {  
  12.     obj = new SomeObject(); //由當前子執行緒建立
  13.     connect(obj, SIGNAL(someSignal()), this, SLOT(someSlot()));  
  14.     obj->callEmitSignal();  
  15.     exec();  
  16. }

同時,在connect函式中由於obj和this(這裡是t2)不是在同一個執行緒中,因此會採用QueuedConnection的方式,其slot函式由this物件所在的執行緒即主執行緒來執行。這裡有一個特別容易誤解的地方,就是這個slot函式雖然是子執行緒SubThread2的一個成員函式,connect操作也是在子執行緒內完成的,但是該函式的執行卻不在子執行緒內,而是在主執行緒內。

那麼如果想讓相應的slot函式在子執行緒內執行,該如何做呢?在子執行緒的run函式中建立obj物件的同時,在執行connect時指定連線方式為DirectConnection,這樣就可以使slot函式在子執行緒中執行,因為DirectConnection的方式始終由sender物件的執行緒執行。如

  1. ////////////////////////////////////////////////////////
  2. // class SubThread3
  3. ////////////////////////////////////////////////////////
  4. SubThread3::SubThread3(QObject* parent)  
  5.     : SubThread(parent)  
  6. {  
  7.     obj=0;  
  8. }  
  9. // reimplement run
  10. void SubThread3::run()  
  11. {  
  12.     obj = new SomeObject();  
  13.     connect(obj, SIGNAL(someSignal()), this, SLOT(someSlot()),  
  14.             Qt::DirectConnection);  
  15.     obj->callEmitSignal();  
  16.     exec();  
  17. }

最後,該程式的執行結果應該是:

  1. "SubThread1::obj's thread is MAIN thread; someSlot executed in MAIN thread;"   
  2. "SubThread2::obj's thread is SUB thread; someSlot executed in MAIN thread;"   
  3. "SubThread3::obj's thread is SUB thread; someSlot executed in SUB thread;"