(8)memory_order_release 发布 , 这也是一种多线程中的内存管理形式:
++ 举例:
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> flag(0);
int data = 0;
void writer() {
data = 42; // 对非原子变量的写
flag.store(1, std::memory_order_release); // 使用 memory_order_release 标记原子操作
}
void reader() {
while (flag.load(std::memory_order_acquire) == 0) {
// 等待
}
// 此时,data 一定已经被写入为 42
std::cout << "Data: " << data << std::endl;
}
int main() {
std::thread t1(writer);
std::thread t2(reader);
t1.join();
t2.join();
return 0;
}
(9) memory_order_acquire 接收:
++举例:
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<bool> ready(false);
int data = 0;
void producer() {
data = 42; // 写入数据
ready.store(true, std::memory_order_release); // 释放数据,使用 memory_order_release
}
void consumer() {
while (!ready.load(std::memory_order_acquire)) {
// 等待数据准备好
}
// 此时,data 一定已经被写入为 42
std::cout << "Data: " << data << std::endl;
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
++ 以上两个举例也提供了宝贵的 atomic《T》 的使用范例 。
(10) memory_order_acq_rel发送与接收 :
++ 举例:
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> flag(0);
int shared_data = 0;
void writer() {
shared_data = 42; // 写入数据
flag.store(1, std::memory_order_release); // 释放数据,使用 memory_order_release
}
void reader() {
int local_flag;
while ((local_flag = flag.load(std::memory_order_acquire)) != 1) {
// 等待数据准备好
}
// 此时,shared_data 一定已经被写入为 42
std::cout << "Shared Data: " << shared_data << std::endl;
flag.store(0, std::memory_order_release); // 重置标志位,使用 memory_order_release
}
void reader_with_acq_rel() {
int expected = 1;
while (!flag.compare_exchange_strong(expected, 0, std::memory_order_acq_rel)) {
// 等待并尝试获取标志位,使用 memory_order_acq_rel
expected = 1; // 如果交换失败,则重新设置期望值
}
// 此时,shared_data 一定已经被写入为 42(因为 compare_exchange_strong 成功了)
std::cout << "Shared Data (with acq_rel): " << shared_data << std::endl;
}
int main() {
std::thread t1(writer);
std::thread t2(reader);
std::thread t3(reader_with_acq_rel);
t1.join();
t2.join();
t3.join();
return 0;
}
(11)
谢谢