C++ STL <mutex> 互斥体

mutex 互斥量

非定时的互斥体类

标准库包含两个非定时的互斥体类

  • std::mutex
  • std::recursive_mutex

每个类都支持下列方法

  • lock() 阻塞直到取到锁
  • trylock() 立刻返回获取锁结果
  • unlock()
  1. 已经拥有std::mutex所有权的线程不能在这个互斥体上再次调用 lock() 和 unlock(),否则可能导致死锁
  2. std::recursive_mutex 的行为与 std::mutex 类似,区别在于能在同一个互斥体上再次调用 lock() 和 unlock(),经常用于递归函数加锁

定时的互斥体类

标准库包含三个定时的互斥体类

  • std::timed_mutex
  • std::recursive_timed_mutex
  • std::shared_timed_mutex

每个类都支持下列方法

  • try_lock_for(rel_time) 在给定相对时间内获取锁,到点返回结果
  • try_lock_util(abs_time) 获取锁直到给定的绝对时间
#include <iostream>
#include <thread>
#include <mutex>
#include <time.h>

using namespace std;

string getTime()
{
    time_t timep;
    time (&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );
    return tmp;
}

void func()
{
    string start = getTime();
    cout << start << endl;

    static mutex m;
    m.lock();
    this_thread::sleep_for(chrono::milliseconds(5000));
    m.unlock();

    string end = getTime();
    cout << end << endl;
}

int main()
{
    thread t1(func);
    thread t2(func);
    t1.join();
    t2.join();

    return 0;
}
2017-08-15 07:56:54
2017-08-15 07:56:54
2017-08-15 07:56:59
2017-08-15 07:57:04
#include <iostream>
#include <thread>
#include <mutex>
#include <time.h>

using namespace std;

string getTime()
{
    time_t timep;
    time (&timep);
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );
    return tmp;
}

void func(int threadId)
{
    string start = getTime();
    cout << start << endl;

    static mutex m;
    if (m.try_lock()) {
        this_thread::sleep_for(chrono::milliseconds(5000));
    }
    else {
        cout<<"thread "<<threadId<<" get lock failed."<<endl;
    }
    m.unlock();

    string end = getTime();
    cout << end << endl;
}

int main()
{
    thread t1(func, 1);
    thread t2(func, 2);
    t1.join();
    t2.join();

    return 0;
}
2017-08-15 08:03:11
2017-08-15 08:03:11
thread 1 get lock failed.
2017-08-15 08:03:11
2017-08-15 08:03:16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值