当前位置:网站首页>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。
边栏推荐
- RockerMQ消息发送与消费模式
- MySQL proficient-01 addition, deletion and modification
- Object含有Copy方法?
- Analysis of orthofinder lineal homologous proteins and result processing
- Static code block vs construction code block
- Design of a solar charge pump power supply circuit
- ThreadLocal digs its knowledge points again
- Shortcut key bug, reproducible (it seems that bug is the required function [funny.Gif])
- 有關二叉樹的一些練習題
- Several cases that do not initialize classes
猜你喜欢
随机推荐
Analysis of key technologies for live broadcast pain points -- second opening, clarity and fluency of the first frame
不会初始化类的几种Case
Installation and use of SVN version controller
prometheus告警流程及相关时间参数说明
内存泄露的最直接表现
Order by injection of SQL injection
i=i++;
JS EventListener
Process 0, process 1, process 2
Conception de plusieurs classes
Analysis log log
Take you to play with the camera module
main()的参数argc与argv
Imx8qxp DMA resources and usage (unfinished)
力扣84柱状图中最大的矩形
ucore lab5
浏览器的markdown插件显示不了图片
When multiple network devices exist, how to configure their Internet access priority?
直接修改/etc/crontab 文件内容,定时任务不生效
Static code block vs construction code block








