Skip to content

Instantly share code, notes, and snippets.

@sonsongithub
Created February 17, 2022 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonsongithub/9976b53c92aef115a3bb2516f4af34b9 to your computer and use it in GitHub Desktop.
Save sonsongithub/9976b53c92aef115a3bb2516f4af34b9 to your computer and use it in GitHub Desktop.
swift concurrency
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