I ran into the following code. I am not sure whether it behaves as intended. The intention is to work around the rule that the continuation can be called once and only once. I really am not sure that there is any guarantee that this hasResumed variable is synchronized between all the threads that may be involved.
For example, I can’t grantee whether the non structured concurrency callbacks are coming back on the same thread with the original hasResumed value?
What about the Task? Honestly I am surprised the compiler doesn’t complain about this one as you are accessing this variable in a concurrent environment?
The other thing I am not sure is guaranteed here is whether any caller of the continuation “stops” the other non structured concurrency things from happening. My guess is not. So someone calling continuation is not “canceling” anything at all.
Is there a better pattern for this timeout on a withCheckedContinuation.
var hasResumed = false
try await withCheckedContinuation { continuation in
longRunningProcess1NonStructuredConcurrency() {
if !hasResumed {
hasResumed = true
continuation.resume()
}
}
longRunningProcess2NonStructuredConcurrency() {
if !hasResumed {
hasResumed = true
continuation.resume()
}
}
// Set up timeout
connectionTimeoutTask = Task {
try? await Task.sleep(nanoseconds: 10_000_000_000) // Wait for 10 seconds
if !hasResumed {
hasResumed = true
continuation.resume(throwing: err)
}
}
}
6