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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM