semaphore 实验

该博客介绍了信号量Semaphore的实现,提供了基于C++的Semaphore类,包含post和wait方法。在32位系统中遇到问题,因此使用了std::atomic、std::mutex和std::condition_variable作为替代。此外,还给出了一个简单的测试示例,展示了如何在接收到SIGINT信号时正确使用Semaphore来控制程序退出。
摘要由CSDN通过智能技术生成

semaphore 实验

/*
 * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
 *
 * This file is part of ZLToolKit(https://github.com/xia-chu/ZLToolKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

#ifndef SEMAPHORE_H_
#define SEMAPHORE_H_

/*
 * 目前发现信号量在32位的系统上有问题,
 * 休眠的线程无法被正常唤醒,先禁用之
 #if defined(__linux__)
#include <semaphore.h>
#define HAVE_SEM
#endif //HAVE_SEM
*/
#include <atomic>
#include <mutex>
#include <condition_variable>
using namespace std;

namespace toolkit {

class semaphore {
public:
    //explicit semaphore(size_t initial = 0) {
    explicit semaphore() {
#if defined(HAVE_SEM)
        sem_init(&_sem, 0, initial);
#else
        _count = 0;
#endif
    }
    ~semaphore() {
#if defined(HAVE_SEM)
        sem_destroy(&_sem);
#endif
    }
    void post(size_t n = 1) {
#if defined(HAVE_SEM)
        while (n--) {
            sem_post(&_sem);
        }
#else
        unique_lock<mutex> lock(_mutex);
        _count += n;
        if(n == 1){
            _condition.notify_one();
        }else{
            _condition.notify_all();
        }
#endif

    }
    void wait() {
#if defined(HAVE_SEM)
        sem_wait(&_sem);
#else
        unique_lock<mutex> lock(_mutex);
        while (_count == 0) {
            _condition.wait(lock);
        }
        --_count;
#endif
    }
private:
#if defined(HAVE_SEM)
    sem_t _sem;
#else
    size_t _count;
    mutex _mutex;
    condition_variable_any _condition;
#endif
};

} /* namespace toolkit */
#endif /* SEMAPHORE_H_ */

 测试例子

#include <signal.h>
#include <string>
#include <sstream>
#include <iostream>
#include <memory>

#include <stdio.h>
#include <unistd.h>


#include <semaphore.h>
 
using namespace std;


int main()
{

    cout<<"hello world"<<endl;
    string m3u8_file ="/tmp/picture/";
	cout<<m3u8_file.substr(0, m3u8_file.rfind('/'))<<endl;


    static toolkit::semaphore sem;
    signal(SIGINT, [](int) { sem.post(); });// 设置退出信号, ctrl+c
    sem.wait();

    cout<<"quit..."<<endl;


    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值