基于线程安全的栈
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:先放一下,具体有空再细说。