Skip to content

Instantly share code, notes, and snippets.

@sonsongithub
Created February 17, 2022 14:20
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/97c0e12441f56a8e1b0bccd8a3aaa82f to your computer and use it in GitHub Desktop.
Save sonsongithub/97c0e12441f56a8e1b0bccd8a3aaa82f to your computer and use it in GitHub Desktop.
Try to use DispatchSemaphore.
class Controller {
var isProcessing = false
let semaphore = DispatchSemaphore(value: 0)
func doit() async {
do {
print("try")
semaphore.signal()
if isProcessing {
print("busy")
semaphore.wait()
return
}
isProcessing = true
semaphore.wait()
try await Task.sleep(nanoseconds: 1000000000)
print("doit")
semaphore.signal()
isProcessing = false
semaphore.wait()
} catch {
print(error)
}
}
}
var con = Controller()
Task {
await con.doit()
task.cancel()
}
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