std::mutex
(C++11),普通互斥锁,可以阻塞式等锁(lock()
)也可以非阻塞式上锁(try_lock()
)std::timed_mutex
(C++11),互斥锁的加时版本,如果在一段时间内(try_lock_for()
)或是在某个时间之前(try_lock_until()
)获取锁成功则成功上锁
//等待到解锁时间后解锁
#include <thread>
#include <iostream>
#include <chrono>
#include <mutex>
std::timed_mutex test_mutex;
void f()
{
auto now=std::chrono::steady_clock::now();
test_mutex.try_lock_until(now + std::chrono::seconds(10));
std::cout << "hello world\n";
}
int main()
{
std::lock_guard<std::timed_mutex> l(test_mutex);
std::thread t(f);
t.join();
}
//锁被释放线程中获取到释放的锁
#include <thread>
#include <iostream>
#include <chrono>
#include <mutex>
std::timed_mutex test_mutex;
void f()
{
auto now=std::chrono::steady_clock::now();
test_mutex.try_lock_until(now + std::chrono::seconds(10));
std::cout << "hello world\n";
}
void unlock()
{
std::lock_guard<std::timed_mutex> l(test_mutex);
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
}
int main()
{
std::thread t(f);
std::thread ll(unlock);
ll.join();
t.join();
return 0;
}
std::recursive_mutex
(C++11),递归互斥锁,在互斥锁的基础上允许持有锁的线程多次通过lock()
或者try_lock()
获取锁,而std::mutex
的拥有者不能继续请求上锁
//多次持续上锁
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
int g_num = 0; // 为 g_num_mutex 所保护
std::recursive_mutex g_num_mutex;
void slow_increment(int id)
{
for (int i = 0; i < 3; ++i) {
g_num_mutex.lock();
++g_num;
std::cout << id << " => " << g_num << '\n';
std::this_thread::sleep_for(std::chrono::seconds(1));
}
for (int i = 0; i < 3; ++i)
{
g_num_mutex.unlock();
}
}
int main()
{
std::thread t1(slow_increment, 0);
std::thread t2(slow_increment, 1);
t1.join();
t2.join();
}
//尝试获得锁
#include <iostream>
#include <mutex>
int main()
{
std::recursive_mutex test;
if (test.try_lock()==true) {
std::cout << "lock acquired" << std::endl;
test.unlock(); // 现在锁定互斥
} else {
std::cout << "lock not acquired" << std::endl;
}
test.lock(); // 再锁定它
if (test.try_lock()) { // 可留下 true
std::cout << "lock acquired" << std::endl;
} else {
std::cout << "lock not acquired" << std::endl;
}
test.unlock();
}
std::recursive_timed_mutex
(C++11),递归锁的加时版本std::shared_mutex
(C++17),共享互斥锁,允许多个线程共享锁(lock_shared()
系列),但只有一个线程能够持有互斥锁(lock()
系列),也就是一般所说的读写锁std::shared_timed_mutex
(C++14),共享互斥锁的加时版本。该版本先于不加时的,因为当时赶着把共享互斥锁加进标准来不及了