boost atomic

文档:

http://www.boost.org/doc/libs/1_53_0/doc/html/atomic.html

Boost.Atomic is a library that provides atomic data types and operations on these data types, as well as memory ordering constraints required for coordinating multiple threads through atomic variables. It implements the interface as defined by the C++11 standard, but makes this feature available for platforms lacking system/compiler support for this particular C++11 feature.

Users of this library should already be familiar with concurrency in general, as well as elementary concepts such as "mutual exclusion".

The implementation makes use of processor-specific instructions where possible (via inline assembler, platform libraries or compiler intrinsics), and falls back to "emulating" atomic operations through locking.

Operations on "ordinary" variables are not guaranteed to be atomic. This means that with int n=0 initially, two threads concurrently executing

void function()
{
  n ++;
}

might result in n==1 instead of 2: Each thread will read the old value into a processor register, increment it and write the result back. Both threads may therefore write 1, unaware that the other thread is doing likewise.

Declaring atomic<int> n=0 instead, the same operation on this variable will always result in n==2 as each operation on this variable is atomic: This means that each operation behaves as if it were strictly sequentialized with respect to the other.

Atomic variables are useful for two purposes:

  • as a means for coordinating multiple threads via custom coordination protocols
  • as faster alternatives to "locked" access to simple variables

Take a look at the examples section for common patterns.

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. int a=0;  
  2. std::cout<<a<<std::endl;  
  3. boost::thread t1([&](){  
  4.       
  5.     for (int cnt=0;cnt<100000;cnt++)  
  6.     {  
  7.         a+=1;  
  8.     }  
  9.   
  10. });  
  11. boost::thread t2([&](){  
  12.     for (int cnt=0;cnt<100000;cnt++)  
  13.     {  
  14.         a-=1;  
  15.     }  
  16.   
  17. });  
  18. t1.join();  
  19. t2.join();  
  20. std::cout<<' '<<a<<std::endl;  

输出:

-3529

编译:要加动态库:

g++ -o atomic_int atomic_int.cpp -std=c++0x -lboost_thread  -lboost_system

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. boost::atomic_int a(0);  
  2. std::cout<<a<<std::endl;  
  3. boost::thread t1([&](){  
  4.       
  5.     for (int cnt=0;cnt<100000;cnt++)  
  6.     {  
  7.         a+=1;  
  8.     }  
  9.   
  10. });  
  11. boost::thread t2([&](){  
  12.     for (int cnt=0;cnt<100000;cnt++)  
  13.     {  
  14.         a-=1;  
  15.     }  
  16.   
  17. });  
  18. t1.join();  
  19. t2.join();  
  20. std::cout<<' '<<a<<std::endl;  


输出

0

原文地址:https://www.cnblogs.com/youxin/p/4325916.html