[英]Is a memory barrier AND volatile ENOUGH to avoid a data race?
I want to see if I am forced to use atomic integers.我想看看我是否被迫使用原子整数。
I have a loop that looks similar to this:我有一个看起来与此类似的循环:
struct loop {
volatile int loop_variable;
volatile int limit;
}
for (int i = loop.loop_variable ; i < loop.limit ; loop.loop_variable++) {
}
Then another thead does this:然后另一个 thead 这样做:
loops.loop_variable = loops.limit;
And issues a memory barrier.并发出 memory 屏障。
Is this multithreaded safe?这个多线程安全吗?
The assembly where there is a data race is between these lines:存在数据竞争的程序集在这些行之间:
// loop.loop_variable = loop.limit;
movl 4+loop.0(%rip), %eax
movl %eax, loop.0(%rip)
And和
// for (int i = loop.loop_variable ; i < loop.limit ; loop.loop_variable++)
movl loop.0(%rip), %eax
movl %eax, -4(%rbp)
jmp .L2
.L3:
movl loop.0(%rip), %eax
addl $1, %eax
movl %eax, loop.0(%rip)
.L2:
movl loop.0(%rip), %eax
cmpl $99999, %eax
jle .L3
movl $0, %eax
There might be a data race between之间可能存在数据竞争
movl loop.0(%rip), %eax
addl $1, %eax
movl %eax, loop.0(%rip)
Since it's three instructions to increment the loop_variable.因为它是增加 loop_variable 的三个指令。 But only one to overwrite the loop variable to the limit.
但只有一个将循环变量覆盖到极限。
Is this multithreaded safe?
这个多线程安全吗?
No.不。
Given鉴于
loops[0].loop_variable = loops[0].limit;
< memory barrier >
in one thread, that memory barrier won't prevent int i = loop.loop_variable
from reading an indeterminate value or loop.loop_variable++
producing nonsense results in another thread.在一个线程中,memory 屏障不会阻止
int i = loop.loop_variable
读取不确定值或loop.loop_variable++
在另一个线程中产生无意义的结果。 Other threads can still potentially "see" the change to loops[0].loop_variable
.其他线程仍然可能“看到”对
loops[0].loop_variable
的更改。 Or parts of the change.或部分改变。
A memory barrier just imposes consistency afterwards - it doesn't do a thing beforehand. memory 障碍只是在事后强加一致性——它事先没有做任何事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.