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

标签 c++ multithreading qt

我想知道是否有办法在 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/

相关文章:

c++ - WIN API 用户权限 C++

java - 从 BlockingQueue 获取时缺少项目

c - 如何在单独的线程中传递 blt vector

c++ - 2个套接字之间无法通信

c++ - RegExp 查找命令行参数

c++ - 如何在 C++ 中检测字符串输入的文件结尾

c++ - 内存映射文件和指向易失对象的指针

c++ - 由于在 C++ 中使用异步 IO 而延迟我的程序而不休眠的替代方法?

java - 当用户命令停止时,如何在 Java 命令提示符中停止线程?

c++ - Qt 包含不同目录中的文件