zoukankan      html  css  js  c++  java
  • C++多线程之互斥锁和超时锁

    #include<iostream>
    #include<thread>
    #include<mutex>
    using namespace std;
    mutex mu;
    void ThreadSource(int i)
    {
            mu.lock();
            cout << "线程" << i << "开始执行了" << endl;
            std::this_thread::sleep_for(1s);
            mu.unlock();
            std::this_thread::sleep_for(3ms); //如果不加延时可能会造成线程资源来不及释放
    }
    int main(int argc,char* argv[])
    {
                   
            for (int i = 0; i < 10; i++)
            {
                   std::thread th(ThreadSource,i+1);
                   th.detach();
            }
            
            getchar();
            return 0;
    }
     
     
     
     
    超时锁
    #include<iostream>
    #include<thread>
    #include<mutex>
    using namespace std;
    timed_mutex mu;
    void ThreadSource(int i)
    {
            for (;;)
            {
                   if (!mu.try_lock_for(chrono::milliseconds(500ms)))
                   {
                           //如果未在规定时间内拿到锁,那么这段代码可能会出现问题,这里可以进行日志的写入,便于调试
                           cout << "线程"<<i<<"超时"<<endl;
                   }
                   cout << "线程" << i << "开始执行了" << endl;
                   std::this_thread::sleep_for(1s);
                   mu.unlock();
                   std::this_thread::sleep_for(3ms); //如果不加延时可能会造成线程资源来不及释放
            }
    }
    int main(int argc,char* argv[])
    {
                   
            for (int i = 0; i < 10; i++)
            {
                   std::thread th(ThreadSource,i+1);
                   th.detach();
            }
            
            getchar();
            return 0;
    }
  • 相关阅读:
    【前端】用 npm 安装 yarn
    【前端】HTML复习巩固
    【前端】JS-删除绑定事件
    【前端】CSS3--动画animation的基本使用,3分钟快速实现一个小动画
    【GitHub】一文入门GitHub的使用,抓紧区交友吧!!
    【git】一文让你入门git的使用
    【前端】外边距合并问题 -- 嵌套盒子
    【前端】height 和 line-height的区别
    前端各种高度宽度视图
    关于 super() , 和 this , bind(this)的粗俗理解
  • 原文地址:https://www.cnblogs.com/SunShine-gzw/p/14530103.html
Copyright © 2011-2022 走看看