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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM