Created
January 27, 2018 13:11
-
-
Save yni3/c605f9d585d28b3eee24e99ac5c370c8 to your computer and use it in GitHub Desktop.
C++11 BinarySemaphore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
SimpleBinarySemaphore.cpp -- implement for SimpleBinarySemaphore.h | |
Copyright 2018 yni3 | |
License : Public Domain (useful for copy and paste for your project) | |
*/ | |
#include "SimpleBinarySemaphore.h" | |
#include <chrono> | |
#include <mutex> | |
#include <condition_variable> | |
//refer | |
//https://cpprefjp.github.io/reference/condition_variable/condition_variable | |
using namespace yni3; | |
struct SimpleBinarySemaphore::Inner | |
{ | |
std::mutex mtx_; | |
std::condition_variable cond_; | |
bool data_ready_; | |
Inner() | |
:data_ready_(false) | |
{ | |
} | |
}; | |
SimpleBinarySemaphore::SimpleBinarySemaphore() | |
:m_pSelf(new Inner()) | |
{ | |
} | |
SimpleBinarySemaphore::~SimpleBinarySemaphore() | |
{ | |
delete m_pSelf; | |
} | |
void SimpleBinarySemaphore::wait() | |
{ | |
std::unique_lock<std::mutex> lk(m_pSelf->mtx_); | |
m_pSelf->cond_.wait(lk, [this] { return m_pSelf->data_ready_; }); | |
} | |
bool SimpleBinarySemaphore::timed_wait(unsigned long long ms) | |
{ | |
std::unique_lock<std::mutex> lk(m_pSelf->mtx_); | |
if (!m_pSelf->cond_.wait_for(lk, std::chrono::milliseconds(ms), [this] { return m_pSelf->data_ready_; })) { | |
return false; | |
} | |
return true; | |
} | |
void SimpleBinarySemaphore::signal() | |
{ | |
{ | |
std::lock_guard<std::mutex> lk(m_pSelf->mtx_); | |
m_pSelf->data_ready_ = true; | |
} | |
m_pSelf->cond_.notify_one(); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
SimpleThread.h -- [C++11] simple use for BinarySemaphore | |
Copyright 2018 yni3 | |
License : Public Domain (useful for copy and paste for your project) | |
*/ | |
#pragma once | |
#ifndef __SIMPLEBINARYSEMAPHORE | |
#define __SIMPLEBINARYSEMAPHORE | |
namespace yni3 { | |
class SimpleBinarySemaphore | |
{ | |
public: | |
SimpleBinarySemaphore(); | |
~SimpleBinarySemaphore(); | |
//stop called thread until signal() called | |
void wait(); | |
//stop called thread until signal() called or timeout | |
bool timed_wait(unsigned long long ms); | |
//wakeup stopped thread | |
void signal(); | |
private: | |
struct Inner; | |
Inner* m_pSelf; | |
}; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment