zoukankan      html  css  js  c++  java
  • C++的mutex

    下面是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 << '
    ';
        }
    }

    作者:cumtchw
    出处:http://www.cnblogs.com/cumtchw/
    我的博客就是我的学习笔记,学习过程中看到好的博客也会转载过来,若有侵权,与我联系,我会及时删除。

  • 相关阅读:
    跨域问题注解解决
    跳出循环到指定位置
    idea model管理
    maven 取本地jar
    注解 元注解
    手动打jar包到maven
    sonar搭建
    jmockit、junit
    注解
    虚拟机指令
  • 原文地址:https://www.cnblogs.com/cumtchw/p/13032798.html
Copyright © 2011-2022 走看看