/****************************************************************************
@File Name: safestack.h
@Author: wangzhicheng
@mail: 2363702560@qq.com
@Created Time: Wed 08 Mar 2017 09:06:48 AM CST
****************************************************************************/
#include <atomic>
#include <memory>
#include <mutex>
#include <stack>
namespace safestack
{
using namespace std;
template<typename T>
class SafeStack
{
private:
const int m_nlimit;
atomic_int m_total;
stack<T>m_data;
mutable mutex m_mutex;
public:
SafeStack(int n = 1000):m_nlimit(n)
{
m_total = 0;
}
SafeStack(const SafeStack &other)
{
lock_guard<mutex>lock(other.m_mutex);
m_data = other.data;
}
SafeStack & operator =(const SafeStack&) = delete;
bool push(T value)
{
if(m_total >= m_nlimit) return false;
++m_total;
lock_guard<mutex>lock(m_mutex);
m_data.push(value);
return true;
}
shared_ptr<T>pop()
{
lock_guard<mutex>lock(m_mutex);
if(m_data.empty()) return nullptr;
--m_total;
shared_ptr<T>const res(make_shared<T>(m_data.top()));
m_data.pop();
return res;
}
bool pop(T &value)
{
lock_guard<mutex>lock(m_mutex);
if(m_data.empty()) return false;
--m_total;
value = m_data.top();
m_data.pop();
return true;
}
bool empty() const
{
lock_guard<mutex>lock(m_mutex);
return m_data.empty();
}
};
}
/****************************************************************************
@File Name: test.cpp
@Author: wangzhicheng
@mail: 2363702560@qq.com
@Created Time: Wed 08 Mar 2017 09:09:30 AM CST
****************************************************************************/
#include "safestack.h"
#include <iostream>
#include <thread>
using namespace safestack;
static const int N = 1000000;
SafeStack<int>ss(N);
void thread_push()
{
while(1)
{
for(int i = 0;i < N;i++) ss.push(i);
}
}
void thread_pop()
{
while(1)
{
shared_ptr<int>ptr = ss.pop();
if(!ptr) cout << "stack is empty...!" << endl;
}
}
int main()
{
thread th0(thread_push);
thread th1(thread_pop);
th0.join();
th1.join();
return 0;
}
CC=g++
all:
$(CC) -std=c++11 -g -o safestackTest test.cpp safestack.h -pthread
threadsafe stack
最新推荐文章于 2025-07-28 11:33:45 发布

290

被折叠的 条评论
为什么被折叠?



