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:
loops.loop_variable = loops.limit;
And issues a memory barrier.
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. 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. Other threads can still potentially "see" the change to loops[0].loop_variable
. Or parts of the change.
A memory barrier just imposes consistency afterwards - it doesn't do a thing beforehand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.