zoukankan      html  css  js  c++  java
  • C++多线程之可重入锁

    #include<iostream>
    #include<thread>
    #include<mutex>
    using namespace std;
    recursive_mutex re;
    void task1()
    {
                re.lock();
                   cout << "处理任务1中..." << endl;
                   std::this_thread::sleep_for(1s);
                   re.unlock();
    }
    void task2()
    {
                re.lock();
                   cout << "处理任务2中..." << endl;
                   std::this_thread::sleep_for(1s);
                   re.unlock();
    }
    class ThreadBase
    {
    public:
            virtual void Start()
            {
                   is_exit = false;
                   th = std::thread(&ThreadBase::Main,this);
            }
            virtual void Stop()
            {
                   is_exit = true;
                   Wait();
            }
            virtual void Wait()
            {
                   if (th.joinable())
                   {
                           th.join();
                   }
            }
            bool get_exit()
            {
                   return is_exit;
            }
            virtual void Main() = 0;
            ThreadBase(int _i):i(_i) {}
            virtual ~ThreadBase() {}
            int i;
    private:
            std::thread th;
            bool is_exit;
    };
    class MyThread:public ThreadBase
    {
    public:
            MyThread(int i):ThreadBase(i) {}
            ~MyThread() override {}
            void Main() override
            {
                   for (;;)
                   {
                           //如果不是可重入锁,那么得先开锁然后才能执行task1,否则会造成死锁
                           //但是如果开锁,也就是在一个线程执行任务时,另一个线程也进来了,如果另一个线程执行了一会就结束了,肯定会
                           //释放锁,而实际上线程一的任务还没执行完
                           re.lock();
                           cout << "线程" << i << "拿到了锁" << endl;
                           task1();
                           task2();
                           re.unlock();
                           std::this_thread::sleep_for(1ms);
                   }
            }
    };
    int main(int argc,char* argv[])
    {
                   MyThread th_one(1);
                   th_one.Start();
                   th_one.Wait();
            
            getchar();
            return 0;
    }
  • 相关阅读:
    我认知的javascript之函数调用
    table 的宽度设置无效
    【转】微信读书排版引擎自动化测试方案
    RocksDB原理及应用
    ElasticSearch 架构及应用简介
    芝加哥大学论文写作指南 简述
    python 常用模块
    Flask-SQLAlchemy安装及设置
    selenium设置程序失败后重启
    获取临时IP加入临时列表使用
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/14530107.html
Copyright © 2011-2022 走看看