首页 > 编程语言 > 详细

C++多线程之互斥锁和超时锁

时间:2021-03-14 00:10:24      阅读:50      评论:0      收藏:0      [点我收藏+]
#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;
}

C++多线程之互斥锁和超时锁

原文:https://www.cnblogs.com/SunShine-gzw/p/14530103.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!