理解多线程(四)--原子量和原子操作

原子量

互斥量可以对于共享变量的访问进行加锁,可以保证对临界区的互斥访问,但加锁总是繁琐的,所以提供了更简单的共享变量保护访问的操作,原子量和原子操作。

原子量的构造

原子量包含在#include 中,对于基本类型,我们可以这样定义原子变量

    std::atomic_bool     abool;  
    std::atomic_int      aint;              
    std::atomic_uint     auint;          
    std::atomic_char     achar;          
    std::atomic_schar    aschar;         
    std::atomic_uchar    auchar;                
    std::atomic_short    ashort;            

也可以使用atomic的模版定义

   std::atomic<int> aint;
   std::atomic<bool> abool;

原子变量不支持拷贝构造,move构造,赋值构造等。

std::atomic<int> aint=0;
std::atomic<int>  aint2= aint;//error 
std::atomic<int>  aint3{std::move(aint)}//error
std::atomic<int>  aint4(aint)//error

简单用法

原子变量已经内部封装好各种操作,=,+=,++等等,可以像基本变量一样操作

#include <iostream>
#include <atomic>
#include <thread>
std::atomic<int> i=0;
void add()
{
	for (int j = 0; j < 100000; ++j)
		i++;
}
int main()
{
	//i.store(0);
	std::vector<std::thread> workers;
	for (int j = 0; j < 10; ++j)
		std::thread(add).detach();
	std::this_thread::sleep_for(std::chrono::microseconds(100000));
	std::cout <<  i << std::endl;
	system("pause");
	return 0;
}

当然atomic是一个模版,所以,也是可以用自定义类型的。比如

class test
{
    int a;
    int b;
};
std::atomic<test> i;

当然不是所有类都支持。

原子操作

自加操作

传入地址

LONG InterlockedIncrement(LONG  *pAddend);

自减操作

LONG InterlockedDecrement(LONG *pAddend);

增加/减某个值

LONG InterlockedExchangeAdd(LONG *pAddend, LONG Increment );

交换

 LONG InterlockedExchange( LPLONG Target, LONG Value );

比较交换

LONG InterlockedCompareExchange(
LPLONG Destination, LONG Exchange, LONG Comperand );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工农村贴膜小哥

我倒是要看看是那个憨憨在给我打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值