码迷,mamicode.com
首页 > 编程语言 > 详细

C++的mutex

时间:2020-06-02 19:00:22      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:bsp   auto   imu   clu   ref   lock   code   include   void   

下面是cppreference网站的的demo

#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;
    }
}

 

C++的mutex

标签:bsp   auto   imu   clu   ref   lock   code   include   void   

原文地址:https://www.cnblogs.com/cumtchw/p/13032798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!