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

原子量

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

原子量的构造

原子量包含在#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 );

猜你喜欢

转载自blog.csdn.net/qq_35651984/article/details/85037953