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;
    }
  • 相关阅读:
    thinkpad的trackpoint在webstorm或phpstorm下滚动条失效的解决方案
    SQL 中操作XML类型数据
    远程调试项目
    2021031520210321 助教一周小结(第七周)
    2021030820210314 助教一周小结(第六周)
    2021030120210307 助教一周小结(第五周)
    2021022220210228 助教一周小结(第四周)
    2021020820210214 助教一周小结(第二周)
    2021021520210221 助教一周小结(第三周)
    2021032220210328 助教一周小结(第八周)
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/14530107.html
Copyright © 2011-2022 走看看