如何保护QThread函数,使其在完成之前的工作之前不会被再次调用

How can I protect a QThread function so it will not be called again until finished its previous work?

本文关键字:工作 调用 保护 何保护 QThread 函数      更新时间:2023-10-16

我使用一个QThread,在它的run方法中,我有一个计时器调用一个函数,该函数执行一些需要一些时间的重操作。通常大于触发定时器的时间间隔(但不总是)。

我需要的是保护这个方法,这样只有当它完成之前的工作时才能调用它。

代码如下:

NotificationThread::NotificationThread(QObject *parent)
           : QThread(parent),
             bWorking(false),
             m_timerInterval(0)
{
}

NotificationThread::~NotificationThread()
{
    ;
}
void NotificationThread::fire()
{
    if (!bWorking)
    {
        m_mutex.lock(); // <-- This is not protection the GetUpdateTime method from invoking over and over.
        bWorking = true;
        int size = groupsMarkedForUpdate.size();
        if (MyApp::getInstance()->GetUpdateTime(batchVectorResult))            
        {
            bWorking = false;
            emit UpdateNotifications();                        
        }            
        m_mutex.unlock();
    }
}

void NotificationThread::run()
{
    m_NotificationTimer = new QTimer();
    connect(m_NotificationTimer, 
            SIGNAL(timeout()),
            this,
            SLOT(fire(),
            Qt::DirectConnection));
    int interval = val.toInt();
    m_NotificationTimer->setInterval(3000);
    m_NotificationTimer->start();
    QThread::exec();
}

// This method is invoked from the main class
void NotificationThread::Execute(const QStringList batchReqList)
{
    m_batchReqList = batchReqList;
    start();
}

你总是可以有一个线程,需要运行的方法连接到一个onDone信号,提醒所有订阅者它已经完成。这样就不会遇到与双锁检查和内存重排序相关的问题。维护每个线程的运行状态

我假设您想保护您的线程不受其他线程的调用。我说的对吗?

这就是QMutex的作用。QMutex为您提供了一个接口来"锁定"线程,直到它被"解锁",从而序列化对线程的访问。您可以选择解锁线程,直到它完成它的工作。但使用它的风险由你自己承担。如果使用不当,QMutex也会出现问题。关于这方面的更多信息,请参考文档。

但是有更多的方法来解决你的问题,比如,@Beached建议一个更简单的方法来解决问题;QThread的实例在完成后会发出一个信号。或者更好的是,在你的线程中做一个bool isDone,如果它完成了,那么它就是true,或者如果它没有完成,它就是false。如果它是true,那么调用该方法是安全的。但是请确保不要在拥有它的线程之外操作isDone。我建议你只在QThread中操作isDone

下面是类文档:link 哈哈,我严重误解了你的问题。对不起。看来你已经完成了我对bWorking的第二个建议。
相关文章: