1. 程式人生 > 實用技巧 >C++11: condition_variable

C++11: condition_variable

C++11: condition_variable

宣告

需要引入標頭檔案

#include <condition_variable>

宣告十分簡單

std::condition_variable _cv;

函式

1、wait函式:

(1)

wait(std::unique_lock <mutex>&lck)

引數是一個std::unique_lock (類似於std::lock_guard自解鎖)

當前執行緒的執行會被阻塞,直到收到 notify 為止。

(2)

wait(std::unique_lock <mutex>&lck,Predicate pred)

第二個引數是一個lambda函式,返回一個bool值

當前執行緒僅在pred=false時阻塞;如果pred=true時,解除阻塞。

2、notify_one:

notify_one():沒有引數、沒有返回值。

解除阻塞當前正在等待此條件的執行緒之一。如果沒有執行緒在等待,則還函式不執行任何操作。如果超過一個,不會指定具體哪一執行緒。

3、notify_all:

notify_all():同上

解除所有等待此條件執行緒

樣例

模擬執行緒掛機/喚醒

#ifndef _CELL_SEMAPHORE_HPP_
#define _CELL_SEMAPHORE_HPP_
#include <condition_variable>
#include <mutex>
class CellSemaphore
{
public:
	CellSemaphore()
	{

	}
	virtual ~CellSemaphore()
	{

	}

private:

	std::condition_variable _cv;

	std::mutex _mutex;

	int _wait = 0;

	int _wakeup = 0;
protected:
	void Wait()
	{
		std::unique_lock<std::mutex> lock(_mutex);
		if (--_wait < 0) 
		{
			_cv.wait(lock, [this]()->bool {
				return _wakeup > 0;
				});//false時阻塞 防止虛假喚醒(執行緒被從等待狀態喚醒了,但其實共享變數(即條件)並未變為true)
			--_wakeup;
		}
	}

	void Wakeup()
	{
		if (++_wait <= 0) //有程序在等待
		{
			++_wakeup;
			_cv.notify_one();
		}
	}
};
#endif // !_CELL_SEMAPHORE_HPP