gpt4 book ai didi

c++ - 如何在Qt中取消暂停线程

转载 作者:行者123 更新时间:2023-11-28 02:00:34 26 4
gpt4 key购买 nike

我想知道是否有办法在 Qt 中取消暂停休眠线程
我使用 QThread::msleep(ms) 函数暂停线程
我想在时间用完之前取消暂停线程
有什么办法吗?

最佳答案

首先,如果您使用的是QSerialPort,您真的不必搞乱线程。您应该异步处理它。所以,你在连接到 readyRead() 信号的插槽中 read(),如果你想在写入之间有一些延迟,请使用 QTimerwrite() in slots connected to its timeout() 信号如@deW1 的评论所建议。

如果你真的想使用多线程,@sploid 的代码方法有很多错误:

互斥锁只能由锁定它的线程解锁。这是documentation for QMutex::unlock()说:

Unlocks the mutex. Attempting to unlock a mutex in a different thread to the one that locked it results in an error. Unlocking a mutex that is not locked results in undefined behavior.

  • A QMutex用于保护对象、数据结构或代码段,以便一次只有一个线程可以访问它。它不用于线程向其他线程发信号
  • A QWaitCondition允许一个线程告诉其他线程某种条件已经满足。这是您需要用来告诉其他线程“取消暂停”的内容。

这是应该如何完成的:

class Thread : public QThread{
public:
Thread(QObject* parent=nullptr):QThread(parent){

}
~Thread(){}

void InterruptWaitState(){
QMutexLocker locker(&mutex);
cond.wakeAll();
}

protected:
void run(){
//waiting thread
QMutexLocker locker(&mutex);
if(cond.wait(&mutex, 5000)){
// unlock from another place
} else {
// exit by timeout
}
}

private:
QMutex mutex;
QWaitCondition cond;
};

关于c++ - 如何在Qt中取消暂停线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39796066/

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