mutex 互斥量
非定时的互斥体类
标准库包含两个非定时的互斥体类
- std::mutex
- std::recursive_mutex
每个类都支持下列方法
- lock() 阻塞直到取到锁
- trylock() 立刻返回获取锁结果
- unlock()
- 已经拥有std::mutex所有权的线程不能在这个互斥体上再次调用 lock() 和 unlock(),否则可能导致死锁
- 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