#include <iostream>
#include <mutex>
#include <thread>
void msg_func()
{
std::mutex mutex;
while(1)
{
std::unique_lock<std::mutex> unique(mutex, std::try_to_lock);
if(unique.owns_lock())
{
std::cout << "owns_lock" << std::endl;
std::cout << "do something" << std::endl;
}
else
{
std::cout << "try_to_lock fail" << std::endl;
}
std::chrono::milliseconds second(1000);
std::this_thread::sleep_for(second);
}
}
int main()
{
std::thread mythread(&msg_func);
getchar();
return 0;
}
$ g++ unique_lock.cpp -std=c++11 -pthread
$ ./a.out
owns_lock
do something
owns_lock
do something