C++的mutex

2020-12-27 10:28

阅读:710

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

下面是cppreference网站的的demo

#include 
#include 
#include string>
#include 
#include 
#include 
 
std::map<:>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<: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 " => "\n;
    }
}

 

C++的mutex

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

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

上一篇:python转义引起的错误

下一篇:归并排序


评论


亲,登录后才可以留言!