Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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