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;
}
posted @ 2021-03-13 19:39  sunshine_gzw  阅读(1210)  评论(0)    收藏  举报