蓝桥ROS机器人之现代C++学习笔记7.5 原子操作
Posted zhangrelay
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了蓝桥ROS机器人之现代C++学习笔记7.5 原子操作相关的知识,希望对你有一定的参考价值。
学习如下代码:
线程竞争和乱序执行
#include <thread>
#include <iostream>
int main()
int a = 0;
volatile int flag = 0;
std::thread t1([&]()
while (flag != 1);
int b = a;
std::cout << "b = " << b << std::endl;
);
std::thread t2([&]()
a = 5;
flag = 1;
);
t1.join();
t2.join();
return 0;
#include <iostream> // std::cout
#include <atomic> // std::atomic, std::memory_order_relaxed
#include <thread> // std::thread
std::atomic_int foo (0);
void set_foo(int x)
foo.store(x,std::memory_order_relaxed); // set value atomically
void print_foo()
int x;
do
x = foo.load(std::memory_order_relaxed); // get value atomically
while (x==0);
std::cout << "foo: " << x << '\\n';
int main ()
std::thread first (print_foo);
std::thread second (set_foo,10);
first.join();
//second.join();
return 0;
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> count = 0;
int main()
std::thread t1([]()
count.fetch_add(1);
);
std::thread t2([]()
count++; // identical to fetch_add
count += 1; // identical to fetch_add
);
t1.join();
t2.join();
std::cout << count << std::endl;
return 0;
#include <atomic>
#include <iostream>
struct A
float x;
int y;
long long z;
;
int main()
std::atomic<A> a;
std::cout << std::boolalpha << a.is_lock_free() << std::endl;
return 0;
clang++ -std=c++2a
g++ -std=c++20
创作打卡挑战赛 赢取流量/现金/CSDN周边激励大奖
以上是关于蓝桥ROS机器人之现代C++学习笔记7.5 原子操作的主要内容,如果未能解决你的问题,请参考以下文章