基于线程安全的栈和队列

基于线程安全的栈

template<typename T>
class threadsafe_stack
{
private:
    stack<T>data;
    mutable mutex m;

public:
    threadsafe_stack(){}
    threadsafe_stack(const threadsafe_stack<T>& other)
    {
        lock_guard<mutex>lock(other.m);
        data = other.data;
    }
    threadsafe_stack<T>& operator= (const threadsafe_stack<T>&) = delete;
    void push(T& val)
    {
        lock_guard lock(m);
        data.push(move(val));
    }

    shared_ptr<T> pop()
    {
        lock_guard lock(m);
        if (data.empty()) throw empty_stack();
        shared_ptr<T>val(shared_ptr<T>(move(data.top())));
        data.pop();
        return val;

    }

    void pop(T& value)
    {
        lock_guard lock(m);
        if (data.empty()) throw empty_stack();
        value = move(data.top());
        data.pop();
    }
    bool empty()
    {
        lock_guard lock(m);
        return data.empty();
    }

};

基于线程安全的队列

template<typename T>
class threadsafe_queue
{
private:
    mutable mutex m;
    queue<T>data;
    condition_variable data_cond;

public:
    threadsafe_queue() {};
    threadsafe_queue(const threadsafe_queue<T>& other)
    {
        lock_guard<mutex>lock(other.m);
        data = other.data;
    }

    void push(T val)
    {
        lock_guard<mutex>lock(m);
        data.push(move(data));
        data_cond.notify_one();
    }

    void wait_and_pop(T& value)
    {
        unique_lock<mutex>lk(m);
        data_cond.wait(lk, [this] {return !data.empty(); });
        value = move(data.front());
        data.pop();
    }

    shared_ptr<T> wait_and_pop()
    {
        unique_lock<mutex>lk(m);
        data_cond.wait(lk, [this] {return !data.empty(); });
        shared_ptr<T>res(move(data.front()));
        data.pop();
        return res;
    }

    bool try_pop(T& value)
    {
        lock_guard<mutex>lock(m);
        if (data.empty())return false;
        value = move(data.front());
        data.pop();
        return true;
    }

    shared_ptr<T> try_pop()
    {
        lock_guard<mutex>lock(m);
        if (data.empty())return nullptr;
        shared_ptr<T>res(move(data.front()));
        data.pop();
        return res;
    }

    bool empty()
    {
        lock_guard<mutex>lock(m);
        return data.empty();
    }
};

ps:先放一下,具体有空再细说。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值