C++11 线程 lock_gurad

The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.

mutex offers exclusive, non-recursive ownership semantics:

  • A calling thread owns a mutex from the time that it successfully calls either lock or try_lock until it calls unlock.
  • When a thread owns a mutex, all other threads will block (for calls to lock) or receive a false return value (for try_lock) if they attempt to claim ownership of the mutex.
  • A calling thread must not own the mutex prior to calling lock or try_lock.

The behavior of a program is undefined if a mutex is destroyed while still owned by any threads, or a thread terminates while owning a mutex. The mutex class satisfies all requirements of Mutex and StandardLayoutType.

std::mutex is neither copyable nor movable.

互斥体类是一个同步原语,可用于保护共享数据免受多个线程同时访问。

互斥锁提供排他的,非递归的所有权语义:

从成功调用锁或try_lock直到调用解锁为止,调用线程拥有一个互斥量。
当一个线程拥有一个互斥锁时,如果所有其他线程试图声明该互斥锁的所有权,它们将阻塞(用于调用锁)或接收到错误的返回值(对于try_lock)。
在调用lock或try_lock之前,调用线程不得拥有互斥量。
如果一个互斥锁仍然由任何线程拥有时被销毁,或者一个线程在拥有一个互斥锁时终止,则程序的行为是不确定的。 互斥锁类满足Mutex和StandardLayoutType的所有要求。

std :: mutex既不可复制也不可移动。

lock:locks the mutex, blocks if the mutex is not available;

锁定互斥锁,如果互斥锁不可用,则阻塞

try_lock

tries to lock the mutex, returns if the mutex is not available

 尝试锁定互斥锁,如果互斥锁不可用,则返回

unlock unlocks the mutex

native_handle返回基础实现定义的本机句柄对象

通常不直接访问std :: mutex:std :: unique_lock,std :: lock_guard或std :: scoped_lock(自C ++ 17起)以更加异常安全的方式管理锁定。


本示例说明了如何使用互斥锁来保护两个线程之间共享的std :: map。

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#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';
	}
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值