头文件duye_semaphore.h
/************************************************************************************
**
* @copyright (c) 2010-2019, Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file duye_semaphore.h
* @version
* @brief
* @author
* @date 2014-06-20
* @note
*
* 1. 2014-06-20 Created this file
*
*/
#pragma once
#include <semaphore.h>
#include <duye_type.h>
namespace duye {
/**
* POSIX semaphore wrapper
*/
class Semaphore {
public:
Semaphore();
~Semaphore();
/**
* @brief wait resouce number > 0
* @return true:successed, false:don't waited resouce
*/
bool wait();
/**
* @brief try wait inc resouce number
* @return true:successed, false:don't waited resouce
*/
bool tryWait();
/**
* @brief wait for timeout
* @parma [in] timeout : millisecond
* @return true:successed, false:don't waited resouce
*/
bool timedWait(const uint64 timeout);
/**
* @brief post semaphore, inc resouce number
* @return true:successed, false:don't waited resouce
*/
bool post();
private:
sem_t m_sem;
};
}
cpp文件duye_semaphore.cpp
/************************************************************************************
**
* @copyright (c) 2010-2019, Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file duye_semaphore.cpp
* @version
* @brief
* @author
* @date 2014-06-20
* @note
*
* 1. 2014-06-20 Created this file
*
*/
#include <time.h>
#include <duye_semaphore.h>
namespace duye {
Semaphore::Semaphore() {
// 2st paramater not equal to zero indicate shared in process
// otherwise shared in all thread in current process
// 3st paramater is the initialization value of semaphore
sem_init(&m_sem, 0, 0);
}
Semaphore::~Semaphore() {
sem_destroy(&m_sem);
}
bool Semaphore::wait() {
return sem_wait(&m_sem) == 0 ? true : false;
}
bool Semaphore::tryWait() {
return sem_trywait(&m_sem) == 0 ? true : false;
}
bool Semaphore::timedWait(const uint64 timeout) {
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
return false;
}
ts.tv_sec += timeout / 1000;
ts.tv_nsec += (timeout % 1000) * 1000000;
return sem_timedwait(&m_sem, &ts) == 0 ? true : false;
}
bool Semaphore::post() {
return sem_post(&m_sem) == 0 ? true : false;
}
}