簡體   English   中英

QTimer的方法'isActive()'是線程安全的嗎?

[英]Is the method 'isActive()' of QTimer threadsafe?

我目前正在考慮QTimer實現的線程安全性。

在我的應用程序中,我使用bool isActive()方法檢查計時器是否正在運行。 當我計划在其他線程中也使用此方法時,我的想法就涉及線程安全性考慮因素。

根據我的研究, bool isActive()方法不是線程安全的。

這是我的假設:

QTimer的實現( QTimer源代碼 )顯示, bool isActive()僅檢查成員變量int id; 大於0:

inline bool isActive() const { return id >= 0; }

此成員變量在構造函數中使用INV_TIMER初始化, INV_TIMER-1的定義。 當計時器啟動時,它將被設置為int QObject::startTimer(int interval)的返回值。

/*! \overload start()
    Starts or restarts the timer with the timeout specified in \l interval.
    If \l singleShot is true, the timer will be activated only once.
*/
void QTimer::start()
{
    if (id != INV_TIMER)                        // stop running timer
        stop();
    nulltimer = (!inter && single);
    id = QObject::startTimer(inter);
}

當我從另一個線程在QTimer::start()期間執行對isActive()的調用時,我認為bool isActive()的返回值可能無效。

我會感謝能夠驗證我的假設的人的意見。

為了達到線程安全,我只需使用互斥體將對計時器的調用包裝起來,如下面的代碼片段所示。

class SensorControl : public QObject
{
    Q_OBJECT

public:
    SensorControl();    // inits and interval-settings are done at implementation

    bool Start()
    {
        QMutexLocker lock(&m_mutexTimer);
        return m_pTimer->start();
    }

    void Stop()
    {
        QMutexLocker lock(&m_mutexTimer);
        return m_pTimer->stop();
    }

    bool IsMeasuring() const
    {
        QMutexLocker lock(&m_mutexTimer);
        return m_pTimer->isActive();
    }

private:

    QMutex m_mutexTimer;
    QTimer* m_pTimer;

};

如果你想調用QTimer::isActive從另一個線程,那么你的解決方案看起來是安全的。 isActive只訪問id成員變量,因此您需要互斥保護所有對id寫入以及從線程中讀取id 您是為isActivestop這樣做的,所以看起來不錯。

請注意,如果您曾經調用其他寫入idQTimer方法,則將獲得未定義的行為。 因此,請注意不要調用諸如QTimer::setInterval()QTimer::~QTimer() (!)之類的東西。 也不要使用Singleshot計時器,因為它將寫入QTimer::timerEvent() id

通常,包裝一個現有的類並添加互斥體是危險的,這是否起作用取決於該類的內部,並且很難在所有情況下進行檢查。 同樣,內部結構可能在下一個Qt版本中發生變化,也許在下一個版本中QTimer::timerEvent()將無條件地更改id ,並且您的解決方案不再是線程安全的。

因此,盡管您的方法可行,但總體上我還是建議不要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM