1. 程式人生 > >《完美Qt》之執行緒呼叫定時器

《完美Qt》之執行緒呼叫定時器

線上程中呼叫定時器

嗨,大家好,我們都知道無論執行緒和定時器,這兩個單獨使用都非常簡單,Qt幫助文件有很詳細的Demo。但是線上程中使用定時器就稍微有點麻煩了,一不注意就容易掉坑裡。

首先理解connect的第五個引數很重要—連線型別

1、connect的第五個引數介紹

Qt::AutoConnection
(Default) If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used. The connection type is determined when the signal is emitted.
Qt::DirectConnection
The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread.
Qt::QueuedConnection
The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
Qt::BlockingQueuedConnection
Same as Qt::QueuedConnection, except that the signalling thread blocks until the slot returns. This connection must not be used if the receiver lives in the signalling thread, or else the application will deadlock.
Qt::UniqueConnection
This is a flag that can be combined with any one of the above connection types, using a bitwise OR. When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (i.e. if the same signal is already connected to the same slot for the same pair of objects). This flag was introduced in Qt 4.6.

2、子執行緒類

    #ifndef CTHREAD_H
    #define CTHREAD_H

    #include <QThread>
    #include <QTimer>
    #include <QDebug>
    class CThread : public QThread
    {
        Q_OBJECT
    public:
        explicit CThread(QObject *parent = 0);
    protected:
        void run()
        {
            m_timer = new
QTimer; //new QTimer(this); //在這個執行緒建立的物件,這個物件就屬於這個執行緒,如果指定父物件,這個物件就在父物件的執行緒 connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimeout()), Qt::DirectConnection); //指定連線方式為DirectConnection,那麼槽函式就在訊號的傳送者的執行緒內執行, //如果指定為QueuedConnection,那麼就在槽函式就在槽函式的物件執行。
//這裡的定時器是在子執行緒裡建立的,所以該物件是子執行緒物件,CThread例項是在main裡建立的,所以這裡的槽函式預設屬於主執行緒 m_timer->start(1000); this->exec(); } signals: public slots: void onTimeout() { //列印執行緒id qDebug() << "sub thread id: " << QThread::currentThreadId(); } private: QTimer *m_timer; }; #endif // CTHREAD_H

3、main函式

    #include "widget.h"
    #include <QApplication>
    #include "cthread.h"
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);

        //C列印主執行緒id號
        qDebug() << "main thread id: " << QThread::currentThreadId();

        CThread thread;
        thread.start(); //啟動子執行緒

        return a.exec();
    }

4、輸出

main thread id:  0x51c
sub thread id:  0x1c38
sub thread id:  0x1c38
sub thread id:  0x1c38
sub thread id:  0x1c38

4、參考