如何在Qt工作线程睡眠
How to sleep in a worker thread in Qt?
我正在创建一个示例来理解Qt中的线程,并希望我的工作线程在每个增量之间睡眠1秒,以便我可以看到调试输出。但是休眠使我的主GUI线程无响应。
这是我在OddCounter
类中的槽函数。
void OddCounter::count()
{
for (int i = 0; i < 10; i++)
{
counter += 2;
qDebug() << counter;
QThread::sleep( 1 );
}
}
调用这个线程的主窗口类是:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
oddCounter = new OddCounter;
connect(this, SIGNAL(startOddCounter()), evenCounter, SLOT(count()), Qt::QueuedConnection );
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
OddCounter oddCounter;
oddCounter.moveToThread( &thread );
thread.start();
emit startOddCounter();
}
问题是,当我按下按钮,计数器工作,并显示下一个增量后,每一秒钟通过,但主窗口是无响应的所有这些时间!这是不对的!我希望我的主窗口是响应的,只有线程应该睡觉。我怎么做呢?
您的代码中有一个错误:您正在创建另一个OddCounter
,您移动到不同的线程,但您的原始oddCounter
信号连接到主线程中仍然存在。你应该这样修改你的代码:
void MainWindow::on_pushButton_clicked()
{
oddCounter->moveToThread( &thread );
thread.start();
emit startOddCounter();
}
相关文章:
- C++为线程工作动态地分割例程
- 自 Windows 10 20H1 以来,具有单独线程的多个窗口停止工作
- 餐饮哲学家问题 - 只有 2 个线程工作
- 工作线程在执行太快后永久休眠
- 唤醒多个线程以在每个条件下工作一次
- Qt::D irectConnection在多线程环境中使用时如何工作?
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 工作线程一直在等待,condition_variable甚至调用了notify_all
- 使用 std::atomic 标志和 std::condition_variable 在工作线程上等待
- SIGABRT 和线程相关的异常,但在调试期间工作正常
- c++线程的安全性和时间效率:为什么有互斥检查的线程有时比没有它的线程工作得更快
- 在多线程工作负载上解释Gperftools的结果
- 我的线程工作不好,它给出了所有结果,最后没有一个接一个,GUI 在线程运行期间挂起?
- BOOST::线程工作线程同步,C++和OpenCV
- 线程工作不正常
- 提升线程工作线程对象在线程完成后的重用
- 线程问题,其中一个线程工作,但导致调用方法不返回
- 线程工作目录
- MFC主UI线程工作和模态对话框
- 用类对象提升线程工作器