c++举一个原子类型为student的例子
以下是一个使用原子类型为student的C++例子:
#include <atomic>
#include <iostream>
#include <string>
struct Student {
std::string name;
int age;
// 构造函数
Student(const std::string& n, int a) : name(n), age(a) {}
};
int main() {
std::atomic<Student> atomicStudent(Student("John", 20));
// 获取当前原子对象的值
Student currentStudent = atomicStudent.load();
// 输出学生的姓名和年龄
std::cout << "Name: " << currentStudent.name << ", Age: " << currentStudent.age << std::endl;
// 修改学生的姓名和年龄
currentStudent.name = "Alice";
currentStudent.age = 22;
// 将修改后的学生对象存储回原子对象
atomicStudent.store(currentStudent);
// 再次获取当前原子对象的值
Student updatedStudent = atomicStudent.load();
// 输出修改后的学生的姓名和年龄
std::cout << "Name: " << updatedStudent.name << ", Age: " << updatedStudent.age << std::endl;
return 0;
}
在这个例子中,我们定义了一个名为Student的结构体,它有两个成员变量name和age,分别表示学生的姓名和年龄。然后,我们使用std::atomic模板类创建了一个原子类型为Student的对象atomicStudent。
我们首先通过调用load()方法获取了当前原子对象的值,并将其存储在currentStudent变量中。然后,我们输出了学生的姓名和年龄。
接下来,我们修改了学生的姓名和年龄,并将修改后的学生对象存储回原子对象atomicStudent中,使用store()方法。然后,我们再次调用load()方法获取当前原子对象的值,并将其存储在updatedStudent变量中。最后,我们输出了修改后的学生的姓名和年龄。
这个例子展示了如何使用原子类型为student的对象,并在多线程环境中确保对该对象的操作的原子性。
原文地址: https://www.cveoy.top/t/topic/i8Ix 著作权归作者所有。请勿转载和采集!