多线程,信号量实现

    ~~~~    前面我写了关于条件变量的一篇博客,我就提到了,std里面没有信号量,当然linux下是有的,windows下也有,只是std里面找不到,然后去网上找,就发现是因为信号量可以直接用锁加条件变量实现它的功能,而且更加安全,我就想可以试一下,然后就写了一个信号量的类,外加例子。
先是实现:

#include <mutex>
#include <condition_variable>

typedef class semaplore{
public:
    semaplore(){
        count = 0;
    }

    inline void signal(){
        std::unique_lock<std::mutex> lock(m);
        count++;
        cond.notify_one();
    }

    inline void wait(){
        std::unique_lock<std::mutex> lock(m);
        cond.wait(lock, [=](){return count > 0;});//这里使用的是仿函数
        count--;
    }

private:
    std::mutex m;
    std::condition_variable cond;
    int count;
};

很简单很简单很简单,主要就是pv操作,signal和wait,下面是使用实例:

#include <mutex>
#include <condition_variable>
#include <thread>
#include <iostream>
#include <queue>

class semaplore{
public:
    semaplore(){
        count = 1;
    }
    ~semaplore(){

    }

    inline void signal(){
        std::unique_lock<std::mutex> lock(m);
        count++;
        cond.notify_one();
    }

    inline void wait(){
        std::unique_lock<std::mutex> lock(m);
        cond.wait(lock, [=](){return count > 0;});
        count--;
    }

private:
    std::mutex m;
    std::condition_variable cond;
    int count;
};

semaplore sem;
std::deque<int> q;

void function_1() {
    int count = 10;
    while (count > 0) {
        sem.wait();
        q.push_front(count);
        sem.signal();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        count--;
    }
}

void function_2() {
    int data = 0;
    while ( data != 1) {
        sem.wait();
        if(q.empty()){
            sem.signal();
            continue;
        }
        data = q.back();
        q.pop_back();
        sem.signal();
        printf("function1 push_front a data to function2: %d \n", data);
    }
}
int main() {
    std::thread t1(function_1);
    std::thread t2(function_2);
    t1.join();
    t2.join();
    return 0;
}

下面是编译加结果

qilimi@qilimi-desktop:~/test$ vim semaplore.cpp
qilimi@qilimi-desktop:~/test$ g++ -o test5 semaplore.cpp -std=c++11 -lpthread
qilimi@qilimi-desktop:~/test$ ./test5
function1 push_front a data to function2: 10
function1 push_front a data to function2: 9
function1 push_front a data to function2: 8
function1 push_front a data to function2: 7
function1 push_front a data to function2: 6
function1 push_front a data to function2: 5
function1 push_front a data to function2: 4
function1 push_front a data to function2: 3
function1 push_front a data to function2: 2
function1 push_front a data to function2: 1
qilimi@qilimi-desktop:~/test$

就这样了,感觉好像好挫呀。
掀桌子了
(╯>д<)╯ ミ ┸┸)`ν゚) ┻━┻
摆好摆好
(#-_-)\┯━┯

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值