std::lock_guard<std::mutex> lock(mutex_);
性能优化是最小使用原则,那么将需要使用的代码块单独拿出来作为函数
mutex_将会自动release 当超出作用范围的时候。
lock_guard 对象的拷贝构造和移动构造(move construction)均被禁用,因此 lock_guard 对象不可被拷贝构造或移动构造。
void safe_increment()
{
std::lock_guard<std::mutex> lock(g_i_mutex);
++g_i;
std::cout << std::this_thread::get_id() << ": " << g_i << '\n';
// g_i_mutex is automatically released when lock goes out of scope
}