C++11 中新增了mutex.用法就是简单的lock,unlock
#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";
g_pages_mutex.lock();
g_pages[url] = result;
g_pages_mutex.unlock();
}
int main()
{
std::thread t1(save_page, "http://foo");
std::thread t2(save_page, "http://bar");
t1.join();
t2.join();
g_pages_mutex.lock(); // not necessary as the threads are joined, but good style
for (const auto &

C++11引入了mutex和lock_guard,lock_guard在构造时自动锁定mutex,在析构时自动解锁,简化了同步代码,尤其在复杂流程中能有效防止资源泄露。通过示例展示了lock_guard如何确保资源的安全管理。
最低0.47元/天 解锁文章
2348

被折叠的 条评论
为什么被折叠?



