4 ms·
I haven't actually been able to find an example program where Swift violates memory safety in a multithreaded environment; I'd love to see an example.
by lalaithion 4y ago
I haven't actually been able to find an example program where Swift violates memory safety in a multithreaded environment; I'd love to see an example.
- tulio_ribeiro 4y agoTo clarify, Swift is considered memory safe in single-threaded environments, but additional steps may be necessary to ensure memory safety in multi-threaded environments. This means that if you are writing Swift code that runs on a single thread, you can be confident that it will not suffer from common memory-related bugs. However, in a multi-threaded environment, multiple threads can access the same memory simultaneously, which can lead to race conditions and other memory-related issues. In order to avoid these problems, developers must use synchronization techniques such as locks or atomic operations to ensure that memory is accessed in a safe and predictable way. I hope this helps to clear up any confusion.
- lalaithion 4y agoIt hasn’t, but not because that isn’t a great explanation. I’m not looking for an explanation; I understand the theory. I’m just not super familiar with Swift — I’m looking for an example program that has a (potential) data race which leads to memory y safety.
- saagarjha 4y agoData races in Swift violate memory safety. That’s why you get EXC_BAD_ACCESS crashes from live data out of them.
- lalaithion 4y agoI don't disbelieve this fact; I'd just like to see a sample program that demonstrates it.
- saagarjha 4y ago$ swiftc - import Dispatch var array = [Int]() DispatchQueue.global().async { while true { array.append(Int.random(in: .min...(.max))) } } DispatchQueue.global().async { while true { let range = 0..<array.count guard !range.isEmpty else { continue } array.remove(at: Int.random(in: range)) } } dispatchMain() $ ./main Segmentation fault: 11 $ ./main main(71894,0x16f103000) malloc: double free for ptr 0x13e808200 main(71894,0x16f103000) malloc: *** set a breakpoint in malloc_error_break to debug Abort trap: 6 $
- lalaithion 4y agoThanks!