当前位置:网站首页>std::memory_order_seq_cst内存序
std::memory_order_seq_cst内存序
2022-06-27 09:11:00 【wangzai6378】
一、在多生产者与多消费者的情况
#include <thread>
#include <atomic>
#include <cassert>
std::atomic<bool> x = {false};
std::atomic<bool> y = {false};
std::atomic<int> z = {0};
void write_x()
{
x.store(true, std::memory_order_seq_cst);
}
void write_y()
{
y.store(true, std::memory_order_seq_cst);
}
void read_x_then_y()
{
while (!x.load(std::memory_order_seq_cst))
;
if (y.load(std::memory_order_seq_cst)) {
++z;
}
}
void read_y_then_x()
{
while (!y.load(std::memory_order_seq_cst))
;
if (x.load(std::memory_order_seq_cst)) {
++z;
}
}
int main()
{
std::thread a(write_x);
std::thread b(write_y);
std::thread c(read_x_then_y);
std::thread d(read_y_then_x);
a.join(); b.join(); c.join(); d.join();
assert(z.load() != 0); // will never happen
}线程a和b是生产者,线程c和d是消费者。所有的生产者(a和b)会发生内存排序;所有的消费者(c和d)在消费时,都是以生产都排好的内存序来执行代码。所以,这里c和d观察a和b时,要么是先x变为true,然后y变为true;要么是先y变为true,再x变为true。无论哪种情况至少为1。
边栏推荐
- 多个类的设计
- How Oracle converts strings to multiple lines
- MATLAB小技巧(19)矩阵分析--主成分分析
- 为智能设备提供更强安全保护 科学家研发两种新方法
- Parameters argc and argv of main()
- 2022.06.26 (LC Luo 6101 Luo determines whether the matrix is an X matrix)
- ThreadLocal digs its knowledge points again
- 针对直播痛点的关键技术解析——首帧秒开、清晰度、流畅度
- Matlab tips (18) matrix analysis -- entropy weight method
- 第十一章 信号(一)- 概念
猜你喜欢

2022.06.26(LC_6100_统计放置房子的方式数)

win10为任意文件添加右键菜单

视频文件太大?使用FFmpeg来无损压缩它

Semi-supervised Learning入门学习——Π-Model、Temporal Ensembling、Mean Teacher简介

MATLAB小技巧(18)矩阵分析--熵权法

1098 Insertion or Heap Sort(堆排序解释)(PAT甲级)

粗读DS-TransUNet: Dual Swin Transformer U-Net for Medical Image Segmentation

DV scroll board width of datav rotation table component
![[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy](/img/d6/119f32f73d25ddd97801f536d68752.png)
[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy

最全H桥电机驱动模块L298N原理及应用
随机推荐
vim 从嫌弃到依赖(20)——global 命令
i=i++;
this,构造器,静态,之间调用,必须搞懂啊!
(original) custom drawable
Parameters argc and argv of main()
高等数学第七章微分方程
Redis transactions
Object含有Copy方法?
了解神经网络结构和优化方法
内存泄露的最直接表现
SVN版本控制器的安装及使用方法
[cloud native] 2.3 kubernetes core practice (Part 1)
Redis master-slave replication and sentinel mode
2022.06.26 (LC Luo 6101 Luo determines whether the matrix is an X matrix)
【生动理解】深度学习中常用的各项评价指标含义TP、FP、TN、FN、IoU、Accuracy
Summary of three basic interview questions
The most direct manifestation of memory leak
视频文件太大?使用FFmpeg来无损压缩它
MATLAB小技巧(18)矩阵分析--熵权法
ucore lab5