造輪子之執行緒鎖監控類的封裝

2021-09-26 16:07:21 字數 1970 閱讀 5570

互斥鎖乙個明顯的缺點是它只有兩種狀態:鎖定和非鎖定。而條件變數通過允許執行緒阻塞和等待另乙個執行緒傳送訊號的方法彌補了互斥鎖的不足,它常和互斥鎖一起配合使用。使用時,條件變數被用來阻塞乙個執行緒,當條件不滿足時,執行緒往往解開相應的互斥鎖並等待條件發生變化。一旦其他的某個執行緒改變了條件變數,他將通知相應的條件變數喚醒乙個或多個正被此條件變數阻塞的執行緒。這些執行緒將重新鎖定互斥鎖並重新測試條件是否滿足。一般說來,條件變數被用來進行執行緒間的同步。

實現

/* 通常執行緒鎖,都通過該類來使用,而不是直接用yr_threadmutex、yr_threadrecmutex 

* * 該類將yr_threadmutex/yr_threadrecmutex 與yr_threadcond結合起來; */

template //t為執行緒鎖型別,p為執行緒條件型別

class yr_monitor

/*** @brief 析夠

*/virtual ~yr_monitor()

/*** @brief 鎖

*/void lock() const

/*** @brief 解鎖, 根據上鎖的次數通知

*/void unlock() const

/*** @brief 嘗試鎖.

** @return bool

*/bool trylock() const

return result;

}/**

* @brief 等待,當前呼叫執行緒在鎖上等待,直到事件通知,

*/void wait() const

catch(...)

_nnotify = 0;

}/**

* @brief 等待時間,當前呼叫執行緒在鎖上等待,直到超時或有事件通知

* * @param millsecond 等待時間

* @return false:超時了, ture:有事件來了

*/bool timedwait(int millsecond) const

catch(...)

_nnotify = 0;

return rc;

}/**

* @brief 通知某乙個執行緒醒來

* * 通知等待在該鎖上某乙個執行緒醒過來 ,呼叫該函式之前必須加鎖,

* * 在解鎖的時候才真正通知

*/void notify()

}/**

* @brief 通知等待在該鎖上的所有執行緒醒過來,

* 注意呼叫該函式時必須已經獲得鎖.

* * 該函式呼叫前之必須加鎖, 在解鎖的時候才真正通知

*/void notifyall()

protected:

/*** @brief 通知實現.

* * @param nnotify 上鎖的次數

*/void notifyimpl(int nnotify) const

else}}

}private:

yr_monitor(const yr_monitor&);

void operator=(const yr_monitor&);

protected:

mutable int _nnotify; //上鎖的次數

mutable p _cond;

t _mutex;

};//普通執行緒鎖

typedef yr_monitoryr_threadlock;

//迴圈鎖(乙個執行緒可以加多次鎖)

typedef yr_monitoryr_threadreclock;

}

這裡互斥鎖和條件變數的配合使用是下面的模式:

pthread_mutex_lock..

.pthread_cond_signal

pthread_mutex_unlock

**互斥鎖為什麼還要和條件變數配合使用

造輪子之執行緒控制類的封裝

執行緒常用方法int pthread join pthread t thread,void retval int pthread detach pthread t thread pthread t pthread self void int pthread create pthread t thre...

造輪子之執行緒安全佇列的封裝

c 中雖然有std queue std deque這些佇列容器,但是不是執行緒安全的,因此我們需要封裝乙個執行緒安全的執行緒佇列。定義template class yr thread queue protected yr threadlock public void push front const...

造輪子之常用函式的封裝

常用函式的封裝 時間操作常用函式 幫助類定義 字串操作封裝class yr common 實現string yr common trim const string sstr,const string s,bool bchar string yr common trimleft const strin...