teonoman

Swift Actors BL Race Condition

Jun 12th, 2021 (edited)
666
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Foundation
  2.  
  3. actor RaceConditionTester {
  4.     private var cache: [String: String] = [:]
  5.  
  6.     public func get(key: String, requestID: UUID = UUID()) async -> String? {
  7.         if let value = self.cache[key] {
  8.             print("[\(requestID.uuidString)] Cache hit")
  9.             return value
  10.         }
  11.  
  12.         print("[\(requestID.uuidString)] Cache miss")
  13.  
  14.         await Task.sleep(1_000_000_000) // 1 sec sleep
  15.  
  16.         self.cache[key] = "value for key '\(key)' (requestID: \(requestID.uuidString))"
  17.  
  18.         return self.cache[key]
  19.     }
  20. }
  21.  
  22. @main
  23. struct Main {
  24.     static func main() async throws {
  25.         let actor = RaceConditionTester()
  26.  
  27.         async let miss1 = actor.get(key: "lul")
  28.         await Task.sleep(100_000_000) // 0.1 sec sleep
  29.         async let miss2 = actor.get(key: "lul")
  30.         await Task.sleep(1_000_000_000) // 1 sec sleep
  31.         async let hit = actor.get(key: "lul")
  32.  
  33.         print("miss1: \(await miss1 ?? "nil")")
  34.         print("miss2: \(await miss2 ?? "nil")")
  35.         print("hit  : \(await hit ?? "nil")")
  36.     }
  37. }
  38.  
  39. // [EFE07659-58CE-4D2D-9554-8047B9469E42] Cache miss
  40. // [6201BE83-CA3F-45E1-BAD4-5F930CB7626B] Cache miss
  41. // miss1: value for key 'lul' (requestID: EFE07659-58CE-4D2D-9554-8047B9469E42)
  42. // miss2: value for key 'lul' (requestID: 6201BE83-CA3F-45E1-BAD4-5F930CB7626B)
  43. // [A8D6241D-F6F5-46AA-A0AF-27328BB9BD6B] Cache hit
  44. // hit  : value for key 'lul' (requestID: 6201BE83-CA3F-45E1-BAD4-5F930CB7626B)
  45.  
RAW Paste Data