超时锁:用来记录线程加锁 解锁 等竞争锁的过程,多用于调试多线程时使用。
启动多个线程,然后,竞争一把超时锁,分别打印记录加锁成功的线程和失败的线程id:文章来源:https://www.toymoban.com/news/detail-643124.html
std::timed_mutex tmtx;
void ThradFunc()
{
while (true)
{
//如果失敗,將睡眠100毫秒,否則搶占鎖成功
//相當於常規鎖mutex :: try_lock()失敗 + sleep()
if(!tmtx.try_lock_for(std::chrono::milliseconds(100)))
{
std::cout << "thread_id = " << std::this_thread::get_id() << " try lock failed" << std::endl;
continue;
}
std::cout << "thread_id = " << std::this_thread::get_id() << " try lock success" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
tmtx.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
int main()
{
for(int i = 0; i < 3; ++i)
{
std::thread t(ThradFunc);
t.detach();
}
getchar();
return 0;
}
打印结果:文章来源地址https://www.toymoban.com/news/detail-643124.html
thread_id = 140532499904256 try lock success
thread_id = 140532508296960 try lock failed
thread_id = 140532491511552 try lock failed
thread_id = 140532508296960 try lock success
thread_id = 140532491511552 try lock failed
thread_id = 140532491511552 try lock failed
thread_id = 140532499904256 try lock failed
thread_id = 140532491511552 try lock success
thread_id = 140532499904256 try lock failed
thread_id = 140532508296960 try lock failed
thread_id = 140532499904256 try lock failed
thread_id = 140532508296960 try lock success
thread_id = 140532499904256 try lock failed
thread_id = 140532491511552 try lock failed
thread_id = 140532499904256 try lock failed
thread_id = 140532491511552 try lock success
thread_id = 140532499904256 try lock failed
thread_id = 140532508296960 try lock failed
thread_id = 140532499904256 try lock failed
thread_id = 140532508296960 try lock success
thread_id = 140532499904256 try lock failed
thread_id = 140532491511552 try lock failed
thread_id = 140532499904256 try lock failed
thread_id = 140532491511552 try lock success
thread_id = 140532499904256 try lock failed
thread_id = 140532508296960 try lock failed
thread_id = 140532499904256 try lock failed
到了这里,关于C++11之超时锁timed_mutex的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!