实现一个多线程的栈(队列是一个意思)

多线程的栈

#include <iostream>
#include <vector>
#include <mutex>
#include <thread>
#include <stack>
#include <exception>
using namespace std;

template<class T>
class MyStack{
public:
    MyStack()= default;
    //判断是否为空
    bool empty(){
        return m_stack.empty();
    }
    void push(const T data){
        lock_guard<mutex> l(m_mutex);
        m_stack.push(data);
    }
    T pop(){
        try{
            lock_guard<mutex> l(m_mutex);
            T data = m_stack.top();
            m_stack.pop();
            try{
                cout<<data<<endl;
            }catch(exception &e){
                cout<<e.what()<<endl;
            }
            return data;
        }catch (exception &e){
            cout<<e.what()<<endl;
        }
    }
private:
    stack<T> m_stack;
    mutex m_mutex;
};

int main() {
    shared_ptr<MyStack<int>> ptr = make_shared<MyStack<int>>();
    thread t1([&](){ptr->push(1);});
    thread t2([&](){ptr->push(2);});
    thread t3([&](){ptr->push(3);});
    thread t4([&](){ptr->push(4);});
    thread t5([&](){ptr->pop();});
    thread t6([&](){ptr->pop();});
    thread t7([&](){ptr->pop();});
    thread t8([&](){ptr->pop();});
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
    t6.join();
    t7.join();
    t8.join();
    return 0;
}

实现一个多线程的栈(队列是一个意思)

上一篇:JAVA 获取 URL 指定参数的值


下一篇:C语言 函数值传递和址传递 - C语言零基础入门教程