6

The following piece of code starts a process that takes one second to finish, and subsequently waits for that process to finish before exiting. For some reason, the following code hangs in p->waitForFinished() even though the process did finish.

#include <QtCore/QProcess>    

class A
{
  public:
    A():
        p(0)
    {
    }

    ~A()
    {
        p->waitForFinished();
        delete p;
    }

    void start()
    {
        p = new QProcess(0);
        p->start("sleep 1");
    }

    QProcess *p;
};

int main(void)
{
  static A a;
  a.start();

  return 0;
}

However, as soon as a is not declared statically, but as follows:

A a;

the waitForFinished() call succeeds. Is this a Qt bug, or is this expected behavour? My suspicion is that some kind of logic required to detect whether an application successfully finished is already destroyed once the destructor of A is called.

4

1 回答 1

10

您已尝试清理由创建的线程QProcess两种不同方式创建的线程,所以这是您的程序中的一个错误。

您已经通过从返回来分离线程main(这会终止进程中的所有线程,如果它们是可连接的,则将它们分离)。

QProcess你已经通过加入它来清理线程waitForFinished.

你可以分离一个线程,也可以加入它,但你不能两者都做,即使是间接的。显然,分离获胜,连接挂起。

这很可能是因为QProcess使用了它自己的终止信号,而不是线程库中内置的终止信号。所以 return frommain在它可以发送终止信号之前终止线程,留下waitForFinished函数等待永远不会发送的信号。

作为一般规则,线程不应在构造函数中创建,也不应在析构函数中清除。这主要是因为这些操作的时间安排需要比可能的更明确的控制。并且它们不应该在main开始之前创建,也不应该在返回之后清理main- 再次因为您需要控制这些事情发生的上下文。

于 2013-01-03T20:54:50.477 回答