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

std::mutex

Defined in header <mutex>

class mutex;

(since C++11)

mutex类是一个同步原语,可用于保护共享数据不被多个线程同时访问。

mutex提供独占的、非递归的所有权语义:

  • 调用线程拥有mutex从它成功调用locktry_lock直到它召唤unlock...
  • 当线程拥有mutex的调用,所有其他线程都将阻塞%28lock%29或收到false返回值%28try_lock%29如果他们试图声称对mutex...
  • 调用线程不能拥有mutex打电话前locktry_lock...

如果mutex在任何线程仍然拥有时被销毁,或者线程在拥有mutex...mutex类满足MutexStandardLayoutType...

std::mutex既不可复制也不可移动。

成员类型

Member type

Definition

native_handle_type(optional)

implementation-defined

成员函数

(constructor)

constructs the mutex (public member function)

(destructor)

destroys the mutex (public member function)

operator= deleted

not copy-assignable (public member function)

锁紧

锁锁互斥锁,如果互斥锁不可用,则阻塞%28公共成员函数%29。

试一试[医]锁试图锁定互斥锁,如果互斥锁不可用,则返回%28公共成员函数%29。

解锁解锁互斥锁%28公共成员函数%29

本机手柄

土生土长[医]句柄返回底层实现定义的线程句柄%28公共成员函数%29

注记

std::mutex通常不能直接访问:std::unique_lock,,,std::lock_guard,或std::scoped_lock%28因为C++17%29以一种更异常安全的方式管理锁定。

此示例演示如何mutex可以用来保护std::map在两个线程之间共享。

二次

代码语言:javascript
复制
#include <iostream>
#include <map>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>
 
std::map<std::string, std::string> g_pages;
std::mutex g_pages_mutex;
 
void save_page(const std::string &url)
{
    // simulate a long page fetch
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::string result = "fake content";
 
    std::lock_guard<std::mutex> guard(g_pages_mutex);
    g_pages[url] = result;
}
 
int main() 
{
    std::thread t1(save_page, "http://foo");
    std::thread t2(save_page, "http://bar");
    t1.join();
    t2.join();
 
    // safe to access g_pages without lock now, as the threads are joined
    for (const auto &pair : g_pages) {
        std::cout << pair.first << " => " << pair.second << '\n';
    }
}

二次

产出:

二次

代码语言:javascript
复制
http://bar => fake content
http://foo => fake content

二次

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

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

扫码关注腾讯云开发者

领取腾讯云代金券