zoukankan      html  css  js  c++  java
  • c++ thread, 模板类,锁的调用实例

    #include<thread>
    #include<condition_variable>
    #include<mutex>
    #include<queue>
    #include<stdio.h>
    
    template <class T>
    class ThreadSafeQueue{
        public:
            void Insert(T value);
            void Popup(T &value);
            bool Empty() const;
    
        private:
            mutable std::mutex mut_;
            std::queue<T> que_;
            std::condition_variable cond_;
    };
    
    template <class T>
    void ThreadSafeQueue<T>::Insert(T value){
        std::lock_guard<std::mutex> lk(mut_);
        que_.push(value);
        cond_.notify_one();
    }
    
    
    template <class T>
    void ThreadSafeQueue<T>::Popup(T &value){
        std::unique_lock<std::mutex> lk(mut_);
        cond_.wait(lk, [this]{return !que_.empty();}); // 如果lamda表达式 [this]{return !que_.empty(); 返回 true, 也就是队列非空,则上锁,继续执行下面的语句;
        value = que_.front();                          // 如果lamda表达式返回False, 也就是队列为空,则解开锁,该线程进入wait,阻塞模式,等待被唤醒
        que_.pop();
    }
    
    
    template <class T>
    bool ThreadSafeQueue<T>::Empty() const{
        std::lock_guard<std::mutex> lk(mut_);
        return que_.empty();
    }
    
    
    int main(){
        ThreadSafeQueue<int> q;
        int value=1;
        std::thread t2(&ThreadSafeQueue<int>::Popup, &q, std::ref(value)); // 传引用参数的时候需要使用引用包装器std::ref
        std::thread t1(&ThreadSafeQueue<int>::Insert, &q, 10);
        printf("%d
    ", value);
        while(!q.Empty());
        t1.join();
        t2.join();
        printf("%d
    ", value);
        return 0;
    }
  • 相关阅读:
    2011年10月小记
    修改模拟器hosts文件
    2011年9月小记
    解决IIS7.5站点不能登录SQLEXPRESS
    EF 4.3 CodeBased Migrations
    2012年5月 小记
    Android对SD卡进行读写
    Tomcat for Eclipse
    ARR2.5 配置反向代理
    作业2浅谈数组求和java实验
  • 原文地址:https://www.cnblogs.com/zengtx/p/11911628.html
Copyright © 2011-2022 走看看