i have one question about swift thread safaty. class Test { public var boolValue = false }
. in above code, the property is safe or not safe if it access in A thread happens-before B thread. then i read the property from B thread. can i got correct value in this case .
is there possible the property value cache into A thread register, B thread can not read correct value even though read the property after A thread done
1 Like
That should not be possible if the accesses are properly ordered by happens-before, i.e. if the threads appropriately synchronize between the events.
3 Likes
let variable = Test()
DispatchQueue.global().async {
variable.boolValue = true
}
sleep(1)
DispatchQueue.global().async {
print("current value \(variable.boolValue)")
}
in above code, write the property in A thread first and read the property in B thread one second later. is automic in swift ? i have a little experience about C++ , value of variables in C++ may cache into CPU Core Cache, so read and write varibles in mutiple thread must use synchronizes
maybe my C++ experience is wrong, correct me if i am wrong
That code would be wrong in Swift, as it would in C++. Really, in some sense that’s a hardware constraint that both languages inherit.
2 Likes