Thread 1:
global b = false
global a = rand()
global b = true
Thread 2:
while !b; end
bad_read1(a) # it is NOT safe to access `a` here!
Would it be thread safe if a is an Atomic?
Thread 1:
global b = Threads.Atomic{Bool}(false)
global a = rand()
global b[] = true
Thread 2:
while !b[]; end
bad_read1(a) # would it be safe to access `a` here?
no, imagine the scheduler puts your thread to sleep right after b becomes true, and it stays asleep while any number of other threads do whatever they want with a and b… then it wakes up… b could be anything as could a.
an atomic operation is on one object, being atomic on b doesn’t mean that after you’ve checked b you can do whatever you want with any number of other variables. That’s what a lock is for.