2011-10-23 6 views
0

두 개의 클래스가 있습니다. 하나는 주 스레드에서 실행되고 GUI 작업을 수행하고 다른 하나는 일부 계산을 수행하고 네트워크 요청을 수행합니다.이 클래스의 소멸자가 호출되지 않는 이유는 무엇입니까?

if(thread.isRunning()) 
{ 
    thread.quit(); 
    thread.wait(); 
} 
: 메인 스레드에서 실행되는 클래스의 소멸자에서

// Create the class that runs in the other thread and move it there 
CServerThread * server = new CServerThread; 
server->moveToThread(&thread); 

// When the thread terminates, we want the object destroyed 
connect(&thread, SIGNAL(finished()), server, SLOT(deleteLater())); 
thread.start(); 

: 여기

// A member of the class that runs in the main thread 
QThread thread; 

는 메인 스레드에서 실행되는 클래스의 초기화 방법에서 미리보기입니다

나는 스레드가 종료되고 CServerThread 클래스의 인스턴스를 파괴합니다. 그러나 CServerThread 클래스의 소멸자가 호출되지 않습니다.

답변

4

QThread::quit()은 해당 스레드에 대한 이벤트 루프를 중지합니다.

리턴 코드 0 (성공)과 함께 스레드의 이벤트 루프를 종료하도록 지시합니다.

는 그러나 활성화하기 위해 "소유"스레드의 이벤트 루프를 QObject::deleteLater() 필요 :

일정 삭제이 객체를.
컨트롤이 이벤트 루프로 반환되면 개체가 삭제됩니다.

개체의 소멸자가 실행되지 않으므로 finished 신호가 너무 빨리 발사됩니다.

#include <QThread> 
#include <iostream> 

class T: public QObject 
{ 
    Q_OBJECT 

    public: 
     QThread thr; 
     T() { 
      connect(&thr, SIGNAL(finished()), this, SLOT(finished())); 
     }; 
     void start() { 
      thr.start(); 
      std::cout << "Started" << std::endl; 
     } 
     void stop() { 
      thr.quit(); 
      std::cout << "Has quit" << std::endl; 
     } 
     void end() { 
      thr.wait(); 
      std::cout << "Done waiting" << std::endl; 
     } 
    public slots: 
     void finished() { 
      std::cout << "Finished" << std::endl; 
     } 
}; 

가 전화 할 경우 :

T t; 
t.start(); 
t.stop(); 
t.end(); 

출력이됩니다 다음 wait 완료 후

Started 
Has quit 
Done waiting 
Finished 

finished가 트리거

아래의 인위적인 예를 생각해 보자. deleteLater 연결이 너무 늦어서 그 스레드의 이벤트 루프가 이미 종료되었습니다.

+0

설명 주셔서 감사합니다. 그러나'deleteLater()'는 내가 만든 QThread가 아니라 주 스레드의 컨텍스트에서 호출되는 것이 아니십니까? –

+0

스레드가 'finished'신호를 내 보냅니다. 서버가 해당 스레드에 속해 있기 때문에 처리는 주 스레드가 아닌 스레드에서 수행됩니다. (맨 아래에있는 [here] (http://doc.qt.nokia.com/4.7/threads-qobject.html) 참조) 자동 연결 설명 – Mat

+0

Qt :: DirectConnection을 사용하지 않으면 슬롯이 주 스레드에서 실행 되나요? 어떤 스레드가'finished()'신호를 내보내고 있습니까? –

관련 문제