Qt thread synchronizing

2017/7/28 14:14:43


Synchronizing QThread

While the purpose of threads is to allow code to run in parallel, there are times where threads must stop and wait for other threads. For example, if two threads try to write to the same variable simultaneously, the result is undefined. The principle of forcing threads to wait for one another is called mutual exclusion. It is a common technique for protecting shared resources such as data. Qt provides low-level primitives as well as high-level mechanisms for synchronizing threads.

QMutex

The purpose of a QMutex is to protect an object, data structure or section of code so that only one thread can access it at a time (this is similar to the Java synchronized keyword).

QMutex

QMutex is the basic method to protect the data access.

QMutex mutex;
class WorkerThread_1 : public QThread {
protected:
    void run() {
        mutex.lock();
        for ( int i = 0; i < 100000; ++i ) {
            value++;
        }
        qDebug() << "Thread 1:" << value;
        mutex.unlock();
    }
};

class WorkerThread_2 : public QThread {
protected:
    void run() {
        mutex.lock();
        for ( int i = 0; i < 200000; ++i ) {
            value++;
        }
        qDebug() << "Thread 2:" << value;
        mutex.unlock();
    }
};

QMutexLocker

The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes. Locking and unlocking a QMutex in complex functions and statements or in exception handling code is error-prone and difficult to debug. If locked, the mutex will be unlocked when the QMutexLocker is destroyed. The above code can be written as:

class WorkerThread_1 : public QThread {
protected:
    void run() {
        QMutexLocker locker( &mutex );
        for ( int i = 0; i < 100000; ++i ) {
            value++;
        }
        qDebug() << "Thread 1:" << value;
    }
};

class WorkerThread_2 : public QThread {
protected:
    void run() {
        QMutexLocker locker( &mutex );
        for ( int i = 0; i < 200000; ++i ) {
            value++;
        }
        qDebug() << "Thread 2:" << value;
    }
};

QWaitCondition

The QWaitCondition class provides a condition variable for synchronizing threads. QWaitCondition allows a thread to tell other threads that some sort of condition has been met. One or many threads can block waiting for a QWaitCondition to set a condition with wakeOne() or wakeAll(). Use wakeOne() to wake one randomly selected condition or wakeAll() to wake them all.

Key functions:
The thread that is woken up depends on the operating system' scheduling policies, and cannot be controlled or predicted.

  • wakeAll(): Wakes all threads waiting on the wait condition.
  • wakeOne(): Wakes one thread waiting on the wait condition.
  • wait(QMutex *lockedMutex, unsigned long time = ULONG_MAX). Flows:
mutex.lock(); // Lock a mutex first.
if ( numUsedBytes == 0 ) {
    // Releases the locked Mutex and waits on the wait condition.
    BufferNotEmpty.wait( &mutex );
}
// The locked Mutex will be returned to the same locked state.
mutex.unlock(); 

Producer-consumer example:

// global variable
const int DATASIZE = 100000;
const int BUFFERSIZE = 8192;

char buffer[BUFFERSIZE];

// Wait Condition
QWaitCondition BufferNotEmpty;
QWaitCondition BufferNotFull;

QMutex mutex;
int numUsedBytes = 0;

// producer
class Producer : public QThread {
protected:
    void run() {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
        for ( int i = 0; i < DATASIZE; ++i ) {
            mutex.lock();
            if ( numUsedBytes == BUFFERSIZE ) {
                BufferNotFull.wait( &mutex );
            }
            mutex.unlock();

            buffer[i%BUFFERSIZE] = "abcd"[(int)qrand() % 4];

            mutex.lock();
            ++numUsedBytes;
            BufferNotEmpty.wakeAll();
            mutex.unlock();
        }
    }
};

class Consumer : public QThread {
protected:
    void run() {
       for ( int i = 0; i < DATASIZE; ++i ) {
           mutex.lock();
           if ( numUsedBytes == 0 ) {
               BufferNotEmpty.wait( &mutex );
           }
           mutex.unlock();

           qDebug() << buffer[i%BUFFERSIZE];

           mutex.lock();
           --numUsedBytes;
           BufferNotFull.wakeAll();
           mutex.unlock();
       }
    }
};

If numUsedBytes == BUFFERSIZE, producer thread will wait until consumer eats some sources(BufferNotFull.wakeAll()). If numUsedBytes == 0, the consumer need to wait until producer produces some sources(BufferNotEmpty.wakeAll()).

QSemaphore

A semaphore is a generalization of a mutex. While a mutex can only be locked once, it's possible to acquire a semaphore multiple times. Semaphores are typically used to protect a certain number of identical resources.

Key functions:

  • QSemaphore::QSemaphore(int n = 0): Creates a new semaphore and initializes the number of resources it guards to n (by default, 0).
  • acquire(n): Tries to acquire n resources guarded by the semaphore. If n > available(), this call will block until enough resources are available.
  • release(n): Returns the number of resources currently available to the semaphore. This number can never be negative.

Same as QWaitCondition example, we rewrite producer-consumer example as follows:

// global variable
const int DATASIZE = 100000;
const int BUFFERSIZE = 8192;
char buffer[BUFFERSIZE];

QSemaphore freeSema(BUFFERSIZE);
QSemaphore usedSema;

class Producer : public QThread {
protected:
    virtual void run() {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

        for ( int i = 0; i < DATASIZE; ++i ) {
            freeSema.acquire();
            buffer[i%BUFFERSIZE] = "ABCD"[(int)qrand()%4];
            usedSema.release();
        }
    }
};

class Consumer : public QThread {
protected:
    virtual void run() {
        for ( int i = 0; i < DATASIZE; ++i ) {
            usedSema.acquire();
            qDebug() << buffer[i%BUFFERSIZE];
            freeSema.release();
        }
    }
};

References

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市驶悟,隨后出現(xiàn)的幾起案子鹰溜,更是在濱河造成了極大的恐慌雳殊,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件解虱,死亡現(xiàn)場離奇詭異撒桨,居然都是意外死亡液样,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門岖赋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來檬果,“玉大人,你說我怎么就攤上這事⊙〖梗” “怎么了杭抠?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長恳啥。 經(jīng)常有香客問我偏灿,道長,這世上最難降的妖魔是什么钝的? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任菩混,我火速辦了婚禮,結(jié)果婚禮上扁藕,老公的妹妹穿的比我還像新娘沮峡。我一直安慰自己,他們只是感情好亿柑,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布邢疙。 她就那樣靜靜地躺著,像睡著了一般望薄。 火紅的嫁衣襯著肌膚如雪疟游。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天痕支,我揣著相機與錄音颁虐,去河邊找鬼。 笑死卧须,一個胖子當著我的面吹牛另绩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播花嘶,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼笋籽,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了椭员?” 一聲冷哼從身側(cè)響起车海,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎隘击,沒想到半個月后侍芝,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡埋同,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年州叠,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片莺禁。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡留量,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情楼熄,我是刑警寧澤忆绰,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站可岂,受9級特大地震影響错敢,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜缕粹,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一稚茅、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧平斩,春花似錦亚享、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至揭璃,卻和暖如春晚凿,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背瘦馍。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工歼秽, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人情组。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓燥筷,卻偏偏與公主長得像,于是被迫代替她去往敵國和親呻惕。 傳聞我的和親對象是個殘疾皇子荆责,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容