简体   繁体   English

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

[英]Launching a while-loop freezes program even if using another thread

In my (Qt-)program I need a continuous request of a value which I get from an external source. 在我的(Qt-)程序中,我需要一个连续的值请求,该值是从外部来源获得的。 But I did not want that this request freezes the whole program, so I created a separate thread for this function. 但是我不希望该请求冻结整个程序,所以我为此函数创建了一个单独的线程。 But even if it is running in a separate thread, the GUI freezes, too. 但是,即使它在单独的线程中运行,GUI也会冻结。 Why? 为什么?

Code for the request function: 请求功能的代码:

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;
        }

    }
}

Read_DPC() returns an int value I want to sent to a lineEdit in my GUI. Read_DPC()返回一个我要发送到GUI中的lineEdit的int值。
The main class looks like 主班看起来像

class DPC: public QThread
{
    Q_OBJECT
public:
    void run();
signals:
    void currentCount(int);
};

This code is called in the main function as: 该代码在主要功能中的调用方式为:

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

How can I prevent this code from freezing my GUI? 如何防止此代码冻结GUI? What am I doing wrong? 我究竟做错了什么? Thanks! 谢谢!

It seems that you code run in GUI thread because you use run() method to start thread, so try to call start() as documentation and many examples said. 似乎您在GUI线程中运行代码是因为您使用run()方法来启动线程,因此请尝试按文档和许多示例所述调用start()

Try: 尝试:

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

Anyways you can call thread() method or currentThread() to see in which thread some objects live. 无论如何,您都可以调用thread()方法或currentThread()来查看某些对象位于哪个线程中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM