首页 > 编程语言 > 详细

C++多线程之可重入锁

时间:2021-03-14 00:07:54      阅读:159      评论:0      收藏:0      [点我收藏+]
#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;
}

C++多线程之可重入锁

原文:https://www.cnblogs.com/SunShine-gzw/p/14530107.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!