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;
    }
  • 相关阅读:
    jQuery形式可以计算,它包含了无线电的变化价格,select价格变化,删除行动态计算加盟
    Codeforces 420 B. Online Meeting
    网站压力测试工具Webbench介绍
    【设计模式】外观模式
    Saiku一个简短的引论
    【iOS】MD5数据加密和网络安全
    FFmpeg资料来源简单分析:libswscale的sws_getContext()
    Unity3D脚本--真实1
    [Android]BaseExpandableListAdapter实现可折叠列表
    如何解决android logcat不打印信息在android开发中
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/14530107.html
Copyright © 2011-2022 走看看