Linux組件封裝(二)中條件變數Condition的封裝

來源:互聯網
上載者:User

標籤:des   style   blog   color   io   使用   strong   資料   sp   

條件變數主要用於實現線程之間的協作關係。

pthread_cond_t常用的操作有:

int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);int pthread_cond_signal(pthread_cond_t *cond);int pthread_cond_broadcast(pthread_cond_t *cond);int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);int pthread_cond_destroy(pthread_cond_t *cond);

我先將Condition類的聲明放在這裡:

#ifndef CONDITION_H_#define CONDITION_H_#include "NonCopyable.h"#include <pthread.h>class MutexLock;class Condition : NonCopyable{public:    Condition(MutexLock &mutex);    ~Condition();    void wait();    void notify();    void notifyAll();private:    pthread_cond_t cond_;    MutexLock &mutex_;};#endif //CONDITION_H_

這裡注意幾點:

1.wait必須在加鎖的條件下調用。

2.notify一次喚醒一個線程,通常用來通知資源可用,

3.notifyAll一次通知多個線程,通常用來通知狀態的改變。濫用broadcast會導致“驚群”問題。

使用wait必須採用while判斷,原因在於:

a) 如果採用if,最多判斷一次。

b) 線程A等待資料,阻塞在full上,那麼當另一個線程放入產品時,通知A去拿資料,此時另一個線程B搶到鎖,直接進入臨界區,取走資源。A重新搶到鎖,(因為採用的是if,所以不會判斷第二次)進去臨界區時,已經沒有資源。

c)防止broadcast的幹擾,如果獲得一個資源,使用broadcast會喚醒所有等待的線程,那麼多個線程被喚醒,但最終只有一個能拿到資源,這就是所謂的“驚群效應”。

cpp代碼實現如下:

#include "Condition.h"#include "MutexLock.h"#include <assert.h>Condition::Condition(MutexLock &mutex)    :mutex_(mutex){    TINY_CHECK(!pthread_cond_init(&cond_, NULL));}Condition::~Condition(){    TINY_CHECK(!pthread_cond_destroy(&cond_));}void Condition::wait(){    assert(mutex_.isLocking()); //wait前必須上鎖    TINY_CHECK(!pthread_cond_wait(&cond_, mutex_.getMutexPtr()));}void Condition::notify(){    TINY_CHECK(!pthread_cond_signal(&cond_));}void Condition::notifyAll(){    TINY_CHECK(!pthread_cond_broadcast(&cond_));}

Linux組件封裝(二)中條件變數Condition的封裝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.