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

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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/208811

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午11:35
下一篇 2023年2月12日 下午11:35

相关推荐