即使使用其他线程,也启动while循环冻结程序

arc*_*pus 0 c++ qt multithreading

在我的(Qt-)程序中,我需要一个从外部源获得的值的连续请求.但我不希望这个请求冻结整个程序,所以我为这个函数创建了一个单独的线程.但即使它在一个单独的线程中运行,GUI也会冻结.为什么?

请求函数的代码:

void DPC::run()
{
    int counts = 0, old_counts = 0;
    while(1)
    {
        usleep(50000);
        counts = Read_DPC();
        if(counts != old_counts)
        {
            emit currentCount(counts);
            old_counts = counts;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Read_DPC()返回我想要发送到GUI中的lineEdit的int值.
主要类看起来像

class DPC: public QThread
{
    Q_OBJECT
public:
    void run();
signals:
    void currentCount(int);
};
Run Code Online (Sandbox Code Playgroud)

此代码在main函数中调用为:

DPC *newDPC = new DPC;
connect(newDPC, SIGNAL(currentCount(int)), SLOT(oncurrentCount(int)));
connect(newDPC, SIGNAL(finished()), newDPC, SLOT(deleteLater()));
newDPC->run();
Run Code Online (Sandbox Code Playgroud)

如何防止此代码冻结我的GUI?我究竟做错了什么?谢谢!

Che*_*byl 5

你似乎在GUI线程中运行代码,因为你使用run()方法启动线程,所以尝试调用start()文档,许多例子说.

尝试:

DPC *newDPC = new DPC;
connect(newDPC, SIGNAL(currentCount(int)), SLOT(oncurrentCount(int)));
connect(newDPC, SIGNAL(finished()), newDPC, SLOT(deleteLater()));
newDPC->start();//not run
Run Code Online (Sandbox Code Playgroud)

无论如何,你可以调用thread()method或currentThread()来查看一些对象所在的线程.