Created
February 17, 2022 14:20
-
-
Save sonsongithub/97c0e12441f56a8e1b0bccd8a3aaa82f to your computer and use it in GitHub Desktop.
Try to use DispatchSemaphore.
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
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