简体   繁体   中英

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. 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. 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.
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? 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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