C++ 原子类型 Student 例子:多线程安全的数据操作
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/lGpx 著作权归作者所有。请勿转载和采集!