C++實作執行緒安全的鏈式堆疊
#include <iostream>
#include<mutex>
#include<thread>
using namespace std;
struct empty_stack : std::exception//例外類的封裝
{
const char* what() const throw();
};
template<class T>
class Stack
{
private:
struct StackNode//結構體
{
T value;
StackNode* next;
};
StackNode* Buynode()//申請節點
{
StackNode* s = (StackNode*)malloc(sizeof(StackNode));
if (NULL == s) exit(EXIT_FAILURE);
memset(s, 0, sizeof(StackNode));
return s;
}
void Freenode(StackNode* p)//釋放節點
{
free(p);
}
private:
StackNode* base;//指標
size_t cursize;//有效元素個數
mutable std::mutex mtx;//互斥鎖
Stack(const Stack&);//拷貝建構式私有化
Stack& operator=(const Stack&);//賦值多載函式私有化
public:
Stack() :base(nullptr) {}//建構式
~Stack() { clear(); }//解構式
size_t get_size() const//獲取有效元素的個數
{
std::lock_guard<std::mutex> lock(mtx);
return cursize;
}
bool is_empty() const//判空
{
return get_size() == 0;
}
void clear()//清空
{
std::lock_guard<std::mutex> lock(mtx);
while (base != nullptr)
{
StackNode* q = base;
base = q->next;
Freenode(q);
}
cursize = 0;
}
void push(const T& x)//入堆疊
{
std::lock_guard<std::mutex> lock(mtx);
StackNode* s = Buynode();
new(&(s->value)) T(x);
s->next = base;
//std::this_thread::sleep_for(std::chrono::seconds(1));
base = s;
cursize += 1;
}
T& top()//獲取堆疊頂元素
{
std::lock_guard<std::mutex> lock(mtx);
return base->value;
}
const T& top()const//獲取堆疊頂元素
{
std::lock_guard<std::mutex> lock(mtx);
return base->value;
}
void pop()//出堆疊
{
std::lock_guard<std::mutex> lock(mtx);
if (base != nullptr)
{
StackNode* q = base;
base = q->next;
Freenode(q);
cursize -= 1;
}
}
};
void thread_funa(Stack<int>& s)//執行緒1
{
for (int i = 0; i < 10; i += 2)
{
cout << i << endl;
s.push(i);
}
}
void thread_funb(Stack<int>& s)//執行緒2
{
for (int i = 1; i < 10; i += 2)
{
cout << i << endl;
s.push(i);
}
}
int main()
{
Stack<int> ist;
thread ta(thread_funa, std::ref(ist));
thread tb(thread_funb, std::ref(ist));
ta.join();
tb.join();
cout << "thread end" << endl;
while (!ist.is_empty())
{
int x = ist.top();
ist.pop();
cout << x << endl;
}
return 0;
}
運行截圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342020.html
標籤:其他
上一篇:2021-10-29
