C++11——std::atomic

std::atomic对int, char, bool等数据结构进行原子性封装,在多线程环境中,对std::atomic对象的访问不会造成竞争-冒险。利用std::atomic可实现数据结构的无锁设计

Atomic.h

// std::atomic 
class CAtomic 
{
public:
	CAtomic() { m_Foo = 0; }
	~CAtomic() {}
	void Run();
	int Func(int x, int y) {}
	void Add_Foo();
	void Sub_Foo();
	
private:
	std::atomic<int> m_Foo;
	std::atomic_flag lock = ATOMIC_FLAG_INIT;
};

 Atomic.cpp

void CAtomic::Run()
{
	printf("========std::atomic==========\n");
	// std::atomic_flag是一个原子的布尔类型,可支持两种原子操作
	std::atomic_flag lock1 = ATOMIC_FLAG_INIT;
	printf("[std::auto] atomic_flag: %d \n", lock1.test_and_set());

	// std::atomic对int, char, bool等数据结构进行原子性封装
	std::thread th2 = std::thread(std::bind(&CAtomic::Add_Foo, this));
	std::thread th1 = std::thread(std::mem_fn(&CAtomic::Sub_Foo), this);
	th1.join();
	th2.join();
}

void CAtomic::Add_Foo()
{
	int nCNt = 5;
	while (nCNt-- )
	{
		m_Foo++;
		//m_Foo = m_Foo + 4;
		while (lock.test_and_set());	//如果atomic_flag对象被设置,则返回true; 如果atomic_flag对象未被设置,则设置之,返回false
		printf("[std::auto] atomic<int> add: %d \n", m_Foo);
		lock.clear();					//清楚atomic_flag对象
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}
}

void CAtomic::Sub_Foo()
{
	int nCNt = 5;
	while (nCNt--)
	{
		m_Foo--;
		// m_Foo = m_Foo - 1;

		while (lock.test_and_set());
		printf("[std::auto] atomic<int> sub: %d \n", m_Foo);
		lock.clear();
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
	}
}

调用:

int main()
{
	//测试std::atomic
	std::shared_ptr<CBase> pAtomic = std::make_shared<CAtomic>();
	pAtomic->Run();			Tab;
	return 0;
}

运行结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值