gpt4 book ai didi

c++ - 即使使用另一个线程,启动 while 循环也会卡住程序

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:50 24 4
gpt4 key购买 nike

在我的 (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;
}

}
}

Read_DPC() 返回一个 int 值,我想发送到 GUI 中的 lineEdit。
主类看起来像

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

这段代码在主函数中被调用为:

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

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

最佳答案

似乎你的代码在 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

无论如何你都可以调用thread()方法或者currentThread()查看某些对象存在于哪个线程中。

关于c++ - 即使使用另一个线程,启动 while 循环也会卡住程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26388663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com