Reentrancy Actor example code

Updated
Nov 6, 2021 5:43 PM
Created
Nov 4, 2021 4:47 AM
Tags
SwiftConcurrency

	func test_reentrancy() async {

    actor MyActor {

      var values: [String] = []

      func operation() async {

        values.append("In")
        try! await Task.sleep(nanoseconds: 2 * 1_000_000_000)
        values.append("Out")

      }

    }

    let actor = MyActor()

    await withTaskGroup(of: Void.self) { group in

      for _ in 0..<10 {
        group.addTask {
          await actor.operation()
        }
      }

    }
    
    print(await actor.values)

  }

["In", "In", "In", "In", "In", "In", "In", "In", "In", "In", "Out", "Out", "Out", "Out", "Out", "Out", "Out", "Out", "Out", "Out"]

actor MyActor {

  var values: [String] = []

  func operation(asyncSleep: UInt64, label: String) async {

    values.append("In: \(label)")
    try! await Task.sleep(nanoseconds: UInt64(asyncSleep) * 1_000_000_000)
    values.append("Out: \(label)")

  }

}

let actor = MyActor()

await withTaskGroup(of: Void.self) { group in

  group.addTask {
    await actor.operation(asyncSleep: 3, label: "1")
  }

  group.addTask {
    await actor.operation(asyncSleep: 1, label: "2")
  }

}

print(await actor.values)

["In: 1", "In: 2", "Out: 2", "Out: 1"]