啥是原子操作用C++代码举例说明
时间: 2024-03-01 20:51:26 浏览: 38
以下是一个简单的 C++ 代码示例,展示了如何使用 std::atomic 类型来实现原子操作:
```c++
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> x(0);
void increment() {
for (int i = 0; i < 100000; i++) {
x++;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "x = " << x << std::endl;
return 0;
}
```
在上面的代码中,我们定义了一个 std::atomic<int> 类型的变量 x,并且启动了两个线程来对它进行加操作。由于 std::atomic 类型提供了原子性操作,因此不需要加锁,多个线程可以同时对 x 进行操作,而不会出现竞态条件。最终输出的结果应该为 200000,即两个线程分别对 x 执行了 100000 次加操作。
相关问题
原子操作C++代码实现
原子操作是指在多线程编程中,确保一个操作的执行是不可分割的,即在同一时刻只能由一个线程执行,以防止数据竞争。在C++11标准中,提供了原子操作的支持,可以使用std::atomic类来实现原子操作。
下面是一个简单的原子操作示例,实现一个计数器:
```
#include <iostream>
#include <atomic>
#include <thread>
std::atomic<int> counter(0);
void increment_counter()
{
for (int i = 0; i < 1000000; ++i)
{
counter++;
}
}
int main()
{
std::thread t1(increment_counter);
std::thread t2(increment_counter);
t1.join();
t2.join();
std::cout << "Counter value: " << counter << std::endl;
return 0;
}
```
在上面的示例中,我们定义了一个std::atomic<int>类型的counter变量作为计数器,并且在increment_counter函数中使用++运算符进行自增操作。由于counter是std::atomic类型,因此++运算符被重载为原子操作,可以确保在同一时刻只有一个线程执行这个操作。
在主函数中,我们创建了两个线程并启动它们,它们会同时对计数器进行自增操作。由于原子操作的支持,我们可以确保计数器的最终值是正确的。
请用C++代码实现原子操作
在 C++11 及以后的标准中,提供了原子操作库 `std::atomic`,可以实现原子操作。下面是一个简单的例子:
```c++
#include <atomic>
#include <iostream>
#include <thread>
std::atomic<int> counter{0};
void increment() {
for (int i = 0; i < 1000; ++i) {
counter++;
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Counter value: " << counter << std::endl;
return 0;
}
```
在这个例子中,我们使用 `std::atomic<int>` 定义了一个原子变量 `counter`,并在两个线程中对其进行累加操作。由于 `counter++` 是一个原子操作,所以不会出现竞态条件,最终得到的 `counter` 值一定是 2000。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)