2 Star 5 Fork 1

beth/ConcurrencySample

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
threadsafe_stack.cpp 1.04 KB
一键复制 编辑 原始数据 按行查看 历史
beth 提交于 2021-02-07 11:52 . Submit sample code.
/**
* @file threadsafe_stack.cpp
* @brief ̰߳ȫstack
*/
#include <iostream>
#include <stack>
#include <mutex>
using namespace std;
template<typename T>
class threadsafe_stack
{
public:
threadsafe_stack() : data(stack<T>()) {}
threadsafe_stack(const threadsafe_stack& other)
{
lock_guard<mutex> lock(other.m);
data = other.data;
}
threadsafe_stack& operator=(const threadsafe_stack&) = delete;
void push(T new_value)
{
lock_guard<mutex> lock(m);
data.push(new_value);
}
std::shared_ptr<T> pop()
{
lock_guard<mutex> lock(m);
if (data.empty()) throw ;
shared_ptr<T> const res(make_shared<T>(data.top()));
data.pop();
return res;
}
void pop(T& value)
{
std::lock_guard<std::mutex> lock(m);
if (data.empty()) throw ;
value = data.top();
data.pop();
}
bool empty() const
{
std::lock_guard<std::mutex> lock(m);
return data.empty();
}
private:
stack<T> data;
mutable mutex m;
};
int main()
{
threadsafe_stack<int> si;
si.push(5);
si.pop();
if (!si.empty())
{
int x;
si.pop(x);
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/bethjohanssen/concurrency-sample.git
git@gitee.com:bethjohanssen/concurrency-sample.git
bethjohanssen
concurrency-sample
ConcurrencySample
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385