在线文档教程
C++
线程支持 | Thread support

std::timed_mutex::lock

STD::定时[医]互斥::锁

void lock((since C++11)

锁定互斥物。如果另一个线程已经锁定互斥对象,则调用lock将阻止执行,直到获得锁为止。

如果lock由已经拥有mutex,行为未定义:例如,程序五月僵局。鼓励可以检测无效使用情况的实现抛出std::system_error有误差条件resource_deadlock_would_occur而不是死锁。

优先unlock()对同一个互斥体的操作同步性中定义的28名ASstd::memory_order%29这次行动。

参数

%280%29

返回值

%280%29

例外

抛出std::system_error当发生错误时,包括来自底层操作系统的错误,这些错误将防止lock不符合它的规格。在抛出任何异常的情况下,互斥锁不会被锁定。

注记

lock()通常不直接调用:std::unique_lockstd::lock_guard用于管理独占锁定。

这个例子显示了如何lockunlock可用于保护共享数据。

二次

#include <iostream> #include <chrono> #include <thread> #include <mutex> int g_num = 0; // protected by g_num_mutex std::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'; g_num_mutex.unlock( std::this_thread::sleep_for(std::chrono::seconds(1) } } int main() { std::thread t1(slow_increment, 0 std::thread t2(slow_increment, 1 t1.join( t2.join( }

二次

可能的产出:

二次

0 => 1 1 => 2 0 => 3 1 => 4 0 => 5 1 => 6

二次

另见

try_locktries to lock the mutex, returns if the mutex is not available (public member function)
try_lock_fortries to lock the mutex, returns if the mutex has beenunavailable for the specified timeout duration (public member function)
try_lock_untiltries to lock the mutex, returns if the mutex has beenunavailable until specified time point has been reached (public member function)
unlockunlocks the mutex (public member function)

c MTX文件[医]锁

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/线程/timeed[医]互斥锁