2

我正在使用 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();
}
4

2 回答 2

0

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

于 2011-08-17T01:40:01.037 回答
-1

我假设您想保护您的线程免受来自另一个线程的调用。我对吗?如果是,那么..

这就是 QMutex 的用途。QMutex 为您提供了一个接口来“锁定”线程,直到它“解锁”,从而序列化对线程的访问。您可以选择解锁线程,直到它完成工作。但使用它需要您自担风险。如果使用不当,QMutex 会出现其自身的问题。有关这方面的更多信息,请参阅文档。

但是还有更多方法可以解决您的问题,例如,@Beached 提出了一种更简单的方法来解决问题;如果完成,您的 QThread 实例将发出一个信号。或者更好的是,bool isDone在你的线程内部创建一个线程,true如果它完成了,或者false没有完成。如果是这样,true那么调用该方法是安全的。但请确保您不要isDone在拥有它的线程之外进行操作。我建议您只isDone在 QThread 内部进行操作。

这是课程文档:链接

大声笑,我严重误解了你的问题。对不起。看来您已经完成了我的第二个建议bWorking

于 2011-12-18T00:27:03.133 回答