0

我有带方法的 QObject,受 QMutex 保护。此方法可以直接从多个线程运行。而且我有另一个 QObject 与两个 QTimers 一起生活在另一个 QThread 中。计时器有不同的时间间隔和第一个对象的 timeout() 调用方法。

可能会发生,计时器同时到期并从同一线程锁定相同的 QMutex。怎么可能?为什么一个 QThread 会与自己并行运行代码?

我通过将计时器放在不同的线程中消除了这个问题。但是为什么QThread可以通过这种方式执行代码呢?

void Module::exec(const QString command)
{
    qDebug("---> run from %X", QThread::currentThreadId());
    QMutexLocker lock(&m_mutex);
    //do the work    
}

class AutoCalibration : public QObject
{
    Q_OBJECT
public:
    explicit AutoCalibration(QObject *parent = 0);
protected:
    QTimer *m_timerTimeout;
    QTimer *m_timerPolling;
    QThread *m_worker;
}

AutoCalibration::AutoCalibration(QObject *parent) : QObject(),
    m_timerTimeout(new QTimer()),
    m_timerPolling(new QTimer()),
    m_worker(new QThread(parent))
{
    m_timerTimeout->moveToThread(m_workwr);
    m_timerTimeout->setInterval(15000);

    m_timerPolling->moveToThread(m_workwr);
    m_timerPolling->setInterval(10000);

    connect(m_timerTimeout, &QTimer::timeout, this, &AutoCalibration::calibrate, Qt::DirectConnection); // run Module::exec() with one argument
    connect(m_timerPolling, &QTimer::timeout, this, &AutoCalibration::requestProp, Qt::DirectConnection); // run Module::exec() with another argument

    connect(m_worker, &QThread::finished, m_timerTimeout, &QTimer::stop);
    connect(m_worker, &QThread::finished, m_timerPolling, &QTimer::stop);

    connect(m_worker, SIGNAL(started()), m_timerTimeout, SLOT(start()));
    connect(m_worker, SIGNAL(started()), m_timerPolling, SLOT(start()));

    m_worker->start();
}
4

0 回答 0