由于使用已被 a 采用的互斥锁的锁,以下代码段是否会导致未污染的行为 a lock_guard
?如果我在同一个片段中使用unique_lock
而不是它会安全吗?lock_guard
我知道有std::unique_lock<T>::lock/unlock()
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
std::mutex m1;
void func(int count ){
std::lock_guard lG{m1};
std::cout << std::this_thread::get_id() << std::endl;
if(count == 1) {
m1.unlock();
std::this_thread::sleep_for(std::chrono::duration<size_t, std::ratio<1, 1>>{6});
m1.lock();
}
std::cout << std::this_thread::get_id() << std::endl;
}
int main()
{
std::thread t1 {func, 1};
std::thread t2 {func, 9};
t1.join();
t2.join();
}