允许超时的互斥量

来源:互联网 发布:windows好用的v翻墙 编辑:程序博客网 时间:2024/05/17 03:47
#include <windows.h>
#include <iostream>
#include <thread>
#include <string>
#include <mutex>
using namespace std;
timed_mutex g_timed_mutex;
void thread1()
{
    unique_lock<timed_mutex> t1(g_timed_mutex);//lock_guard只是提供了对互斥量最基本的加解锁封装,而unique_lock提供了多种构造方法,使用起来更加灵活,对于允许超时的互斥量需要使用unnique_lock来包装。
    ::Sleep(3000);//睡眠3秒
    puts("thread1");
}
void thread2()
{
    unique_lock<timed_mutex> t1(g_timed_mutex, chrono::milliseconds(1000));//超出时间1秒
    puts("thread2");
}
int main(int argc, char* argv[])
{
    thread t1(thread1);
    Sleep(100);//让线程1先启动
    thread t2(thread2);//如果线程1对共享资源的访问时间比较长,这时线程2可能等不了那么久,所以设置一个超时时间,在超时时间内如果线程1中的互斥量还没有解锁,线程2就不等了,继续往下执行。
    t1.join();
    t2.join();

    system("pause");
    return 0;
}
0 0
原创粉丝点击