Changing and accessing data in different threads

Hi all :slight_smile:

In the docs is written that the following is not safe.

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?

I believe it is necessary to use one of the atomic_ methods documented here to be safe.

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.

Thank you. That makes sense!