30、memory-order-relaxed
使用C++标准库中的std::thread
来创建线程,并且使用std::atomic
来确保变量的原子性。
#include <iostream>
#include <thread>
#include <atomic>std::atomic<int> x = 0; // global variable
std::atomic<int> y = 0; // global variablevoid thread1() {int r1 = y.load(std::memory_order_relaxed); // Ax.store(r1, std::memory_order_relaxed); // B
}void thread2() {int r2 = x.load(std::memory_order_relaxed); // Cy.store(42, std::memory_order_relaxed); // D
}int main() {std::thread t1(thread1);std::thread t2(thread2);t1.join();t2.join();std::cout << "x: " << x.load() << ", y: " << y.load() << std::endl;return 0;
}
这个代码创建了两个线程,分别执行thread1
和thread2
函数。std::atomic
确保了对变量x
和y
的操作是原子的。
最后,主线程等待两个线程完成,并输出变量x
和y
的值。