gpt4 book ai didi

c++ - 这里的顺序一致性有什么问题?

转载 作者:行者123 更新时间:2023-11-30 01:46:32 27 4
gpt4 key购买 nike

我正在研究 C 和 C++ 中的无锁算法,最近偶然发现了一个我不太理解的行为。如果你有下面的代码,运行它会给你类似的东西

reader startedwriter startediters=79895047, less=401131, eq=48996928, more=30496988

Aren't std::atomics are expected to be sequentially-consistent? If so, why does the reader sometimes see b being updated before a? I also tried to do various tricks involving memory fences with no success. The full compilable code can be seen at https://github.com/akamaus/fence_test

What's wrong with the example?

std::atomic<uint> a(0);
std::atomic<uint> b(0);

volatile bool stop = false;

void *reader(void *p) {
uint64_t iter_counter = 0;
uint cnt_less = 0,
cnt_eq = 0,
cnt_more = 0;

uint aa, bb;


printf("reader started\n");

while(!stop) {
iter_counter++;
aa = a.load(std::memory_order_seq_cst);
bb = b.load(std::memory_order_seq_cst);
if (aa < bb) {
cnt_less++;
} else if (aa > bb) {
cnt_more++;
} else {
cnt_eq++;
}
}
printf("iters=%lu, less=%u, eq=%u, more=%u\n", iter_counter, cnt_less, cnt_eq, cnt_more);

return NULL;
}

void *writer(void *p) {
printf("writer started\n");
uint counter = 0;
while(!stop) {
a.store(counter, std::memory_order_seq_cst);
b.store(counter, std::memory_order_seq_cst);
counter++;
}
}

最佳答案

顺序一致的内存排序意味着所有线程观察到的(使用 seq cst 操作的原子对象的)修改顺序是一致的。该程序的行为就好像所有这些操作都交织在一个单一的总顺序中。考虑以下情况:


Writer Reader       a == 0a = 1b = 1       b == 1

结果:aa < bb .


Writer Readera = 1       a == 1       b == 0b = 1

结果:aa > bb


带锁,例如一个mutex ,您可以确保操作不会交错。

关于c++ - 这里的顺序一致性有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33017606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com