Created
February 17, 2022 13:19
-
-
Save sonsongithub/9976b53c92aef115a3bb2516f4af34b9 to your computer and use it in GitHub Desktop.
swift concurrency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
actor Flag { | |
var value = false | |
func free() { | |
value = false | |
} | |
func check() -> Bool { | |
if value == false { | |
value = true | |
return false | |
} | |
return true | |
} | |
} | |
class Controller { | |
var flag = Flag() | |
func doit() async { | |
do { | |
if await flag.check() { | |
print("busy") | |
return | |
} | |
try await Task.sleep(nanoseconds: 1000000000) | |
print("doit") | |
await flag.free() | |
} catch { | |
print(error) | |
} | |
} | |
} | |
var con = Controller() | |
Task { | |
await con.doit() | |
} | |
Task { | |
await con.doit() | |
} | |
Task { | |
await con.doit() | |
} | |
Task { | |
await con.doit() | |
} | |
let task = Task { | |
do { | |
try await Task.sleep(nanoseconds: 2000000000) | |
await con.doit() | |
} catch { | |
print(error) | |
} | |
} | |
Task { | |
try await Task.sleep(nanoseconds: 4000000000) | |
task.cancel() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment