C++跨平台事件機制實現


今天看到有人在討論C++標准沒有提供類似操作系統層次的事件通知機制,如windows的事件內核對象。其實我想說的事,C++11標准里的互斥量及條件變量已經夠幫我們實現類似的功能了。

剛編寫了一個事件通知類新鮮出爐,供大家把玩一下,一起學習並發線程的編寫。寫的有不好的地方,請一定要不吝惜指出來,我會改正,謝謝!

廢話不說,上代碼,為了夠能編譯成功,請用支持C++11的編輯器,我用的是Vs2012。為了湊夠150字,用例代碼就直接貼這里:

#include "event.hpp"

event my_event;

void threadproc3()
{
my_event.wait();
cout << "threadproc3\n";
}

void threadproc4()
{
my_event.wait();
cout << "threadproc4\n";
}

int main()
{
my_event.notify_all();

thread t1(threadproc3);
thread t2(threadproc4);

//while(true)
{
system("pause");
my_event.notify_all();
}


t1.join();
t2.join();

return 0;
}

輸出結果:

完整代碼:

//event.hpp

#ifndef EVENT_INCLUDE
#define EVENT_INCLUDE

#include <mutex>
#include <condition_variable>
#include <atomic>

// 利用C++11的鎖與條件變量實現跨平台的事件通知機制
class event
{
public:
    event()
    {
        _state = false;
    }
    
    void wait()
    {
        // 這里的狀態設置不使用強同步,允許同一時刻多個線程喚醒也沒什么問題
        if (_state==true)
        {
            _state = false;
            return;
        }
        std::unique_lock<std::mutex> _lock(_mutex);
        _var.wait(_lock);
        _state = false;
    }

    template<typename T>
    bool wait_for(T&& t)
    {
        // 這里的狀態設置不使用強同步,允許同一時刻多個線程喚醒也沒什么問題
        if (_state==true)
        {
            _state = false;
            return true;
        }
        std::unique_lock<std::mutex> _lock(_mutex);
        std::cv_status::cv_status re = _var.wait_for(_lock,std::forward<T>(t));
        if (re!=std::cv_status::cv_status::timeout)
        {
            _state = false;
            return true;
        }
        return false;
    }

    template<typename T>
    bool wait_util(T&& t)
    {
        // 這里的狀態設置不使用強同步,允許同一時刻多個線程喚醒也沒什么問題
        if (_state==true)
        {
            _state = false;
            return true;
        }
        std::unique_lock<std::mutex> _lock(_mutex);
        std::cv_status::cv_status re = _var.wait_until(_lock,std::forward<T>(t));
        if (re!=std::cv_status::cv_status::timeout)
        {
            _state = false;
            return true;
        }
        return false;
    }

    void notify_all()
    {
        _var.notify_all();
        _state = true;
    }

    void notify_once()
    {
        _var.notify_one();
        _state = true;
    }

private:
    event(const event&);
    event& operator=(const event&);
    event(event&&);

protected:
    std::mutex _mutex;
    std::condition_variable _var;
    std::atomic<bool> _state; // 件事的狀態
};


#endif

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM