即使使用另一个线程,启动while循环也会冻结程序
Launching a while-loop freezes program even if using another thread
在我的(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++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 了解如何在不冻结事件循环的情况下在 QThread 中休眠/等待
- 在 openGL 中播放音频而不冻结绘制循环
- 螺纹在循环中冻结
- 程序冻结/循环
- 如何创建非冻结无限循环
- 确定在时间关键型循环中冻结 200 毫秒的原因
- 即使使用另一个线程,启动while循环也会冻结程序
- c++格式在while循环期间冻结