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 << '\n'; } }
作者:cumtchw
出处:http://www.cnblogs.com/cumtchw/
我的博客就是我的学习笔记,学习过程中看到好的博客也会转载过来,若有侵权,与我联系,我会及时删除。