// // LockedTests.swift // PHP Monitor // // Created by Nico Verbruggen on 23/11/2025. // Copyright © 2025 Nico Verbruggen. All rights reserved. // import Testing import Foundation @Suite("Locked Thread Safety") struct LockedTests { @Test("Reading and writing from a single thread works correctly") func singleThreadReadWrite() { let locked = Locked(0) locked.value = 42 #expect(locked.value == 42) locked.value = 100 #expect(locked.value == 100) } @Test("Concurrent writes do not cause data races") func concurrentWritesAreThreadSafe() async { let locked = Locked(0) let iterations = 1000 // Spawn many concurrent tasks that all increment the counter await withTaskGroup(of: Void.self) { group in for _ in 0.. 0, "Value should have been incremented") #expect(locked.value <= iterations, "Value should not exceed iterations") } @Test("Concurrent reads and writes do not crash") func concurrentReadsAndWritesDoNotCrash() async { let locked = Locked<[String]>([]) let iterations = 500 await withTaskGroup(of: Void.self) { group in // Writers for i in 0..([:]) let iterations = 100 await withTaskGroup(of: Void.self) { group in // Multiple tasks replacing the entire dictionary for i in 0..(0) let taskCount = 10 let incrementsPerTask = 100 await withTaskGroup(of: Void.self) { group in for _ in 0..= 0 && finalValue < 1000, "Value should be within expected range") } }