首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::mutex::unlock

void unlock();

?

(since C++11)

打开互斥锁。

互斥锁必须由当前的执行线程锁定,否则,行为是未定义的。

这次行动同步性中定义的28名ASstd::memory_order%29获得相同互斥对象所有权的任何后续锁操作。

参数

%280%29

返回值

%280%29

例外

%280%29

注记

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

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

二次

代码语言:javascript
复制
#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();
}

二次

可能的产出:

二次

代码语言:javascript
复制
0 => 1
1 => 2
0 => 3
1 => 4
0 => 5
1 => 6

二次

另见

lock

locks the mutex, blocks if the mutex is not available (public member function)

try_lock

tries to lock the mutex, returns if the mutex is not available (public member function)

c MTX文件[医]解锁

代码语言:txt
复制
 ? cppreference.com

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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com