Linux semaphore 封装实现

头文件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;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道知极限编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值