boost atomic
2015-03-10 14:18 youxin 阅读(507) 评论(0) 编辑 收藏 举报文档:
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.
- int a=0;
- std::cout<<a<<std::endl;
- boost::thread t1([&](){
- for (int cnt=0;cnt<100000;cnt++)
- {
- a+=1;
- }
- });
- boost::thread t2([&](){
- for (int cnt=0;cnt<100000;cnt++)
- {
- a-=1;
- }
- });
- t1.join();
- t2.join();
- std::cout<<'\t'<<a<<std::endl;
输出:
-3529
编译:要加动态库:
g++ -o atomic_int atomic_int.cpp -std=c++0x -lboost_thread -lboost_system
- boost::atomic_int a(0);
- std::cout<<a<<std::endl;
- boost::thread t1([&](){
- for (int cnt=0;cnt<100000;cnt++)
- {
- a+=1;
- }
- });
- boost::thread t2([&](){
- for (int cnt=0;cnt<100000;cnt++)
- {
- a-=1;
- }
- });
- t1.join();
- t2.join();
- std::cout<<'\t'<<a<<std::endl;
输出
0
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2014-03-10 haskell趣学指南笔记1
2014-03-10 haskell入门
2014-03-10 MySQL全连接(Full Join)实现,union和union all用法
2014-03-10 haskell 开发环境配置
2013-03-10 转:网页设计常用尺寸大全
2012-03-10 php mail函数一段好的代码