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;
}
posted @ 2021-03-13 19:41  sunshine_gzw  阅读(2496)  评论(0编辑  收藏  举报