【问题标题】:Launching a while-loop freezes program even if using another thread即使使用另一个线程,启动 while 循环也会冻结程序
【发布时间】:2014-10-15 17:37:59
【问题描述】:

在我的 (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() 返回一个我想发送到我的 GUI 中的 lineEdit 的 int 值。
主类看起来像

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

这段代码在main函数中调用如下:

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

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

【问题讨论】:

  • 你究竟是如何启动一个单独的线程的?
  • 我想通过创建一个从 QThread 派生的子类?根据一些线程(stackoverflow.com/questions/14545961/…)或(stackoverflow.com/questions/16501284/…
  • 为什么要从主线程调用run?你不想让其他线程调用run吗?这不是从 QThread 派生的全部意义吗?
  • 不使用run应该如何启动子线程?我尝试使用start,但这也不起作用(我只是将run 替换为start,如果正确的话)
  • @arc_lupus 一次一个错误。修复对run 的调用,然后重新测试,尽可能详细地描述修复该错误后出现的问题。

标签: c++ multithreading qt


【解决方案1】:

您的代码似乎在 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() 来查看某些对象存在于哪个线程中。

【讨论】:

  • 使用start() 也会导致冻结。
  • @arc_lupus 将 qDebug()
  • @arc_lupus 我现在运行相同的代码并尝试理解问题。请告诉我你在运行时会看到什么(在 while 循环中):qDebug() << thread() << currentThread();
  • @arc_lupus 当我使用 run 而不是启动我的 GUI 冻结时,调用 run 是错误的,现在我试着理解为什么 start() 不适合你。
  • @N1ghtLight 我会的,这很酷。投票评论没有任何结果,但您的贡献不会被遗忘或遗漏;)
猜你喜欢
  • 2023-04-06
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
相关资源
最近更新 更多