2011-12-16 42 views
0

下面的代碼會崩潰,甚至掛起linux,有關它的任何想法?爲什麼應用程序崩潰,如果eventlist中有太多事件?

#include <QCoreApplication> 
#include <QString> 
#include <QMap> 
#include <QList> 
#include <QDebug> 
#include <QThread> 
#include <QTest> 


long long emited=0; 
long long handled=0; 
int flag=0; 

class A:public QThread 
{ 
    Q_OBJECT 
public: 
    A(QString n):n_(n){moveToThread(this);} 
    void run() { 
     QMetaObject::invokeMethod(this, "g",Qt::QueuedConnection); 
     exec(); 
    } 
    QString n_; 
signals: 
    void as(); 
public slots: 
    void g(){ 
     while(1) { 
      ++emited; 
      emit as(); 
     } 
    } 
}; 

class Main:public QObject 
{ 
    Q_OBJECT 
public slots: 
    void s0(){} 
    void s1(){ 
     ++flag; 
     ++handled; 
     A *obj = qobject_cast<A*>(sender()); 
     int nothandle=emited-handled; 
     --flag; 
     if(obj) { 
      qDebug()<<"s1"<<obj->n_<<"not handled:"<<nothandle<<flag; 
     } 
    } 
}; 



int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 
    QThread th1,th2; 
    A a1("a1"),a2("a2"); 
    Main m; 
    QObject::connect(&a1,SIGNAL(as()),&m,SLOT(s1()),Qt::QueuedConnection); 
    QObject::connect(&a2,SIGNAL(as()),&m,SLOT(s1()),Qt::QueuedConnection); 
    a1.start(); 
    a2.start(); 
    return a.exec(); 
} 
+2

哦,男孩......不......真的不要做moveToThread(this)!這是真的錯了http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/ – 2011-12-16 10:27:57

回答

2

它崩潰,因爲這一點:

while(1) { 
    ++emited; 
    emit as(); 
} 

Qt的信號隊列不斷增長,但你是不是讓Qt的處理信號,因此它會繼續下去,直到它崩潰。使用QTimer避免凍結您的應用程序並讓Qt處理您的信號。

相關問題