Skip to content

[Concurrency] implement withCancellationHandler via records #36032

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions include/swift/Runtime/Concurrency.h
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,17 @@ size_t swift_task_getJobFlags(AsyncTask* task);
SWIFT_EXPORT_FROM(swift_Concurrency) SWIFT_CC(swift)
bool swift_task_isCancelled(AsyncTask* task);

/// Create and add an cancellation record to the task.
SWIFT_EXPORT_FROM(swift_Concurrency) SWIFT_CC(swift)
CancellationNotificationStatusRecord*
swift_task_addCancellationHandler(
AsyncTask *task, CancellationNotificationStatusRecord::FunctionType handler);

/// Remove the passed cancellation record from the task.
SWIFT_EXPORT_FROM(swift_Concurrency) SWIFT_CC(swift)
void swift_task_removeCancellationHandler(
AsyncTask *task, CancellationNotificationStatusRecord *record);

using TaskLocalValuesFragment = AsyncTask::TaskLocalValuesFragment;

/// Get a task local value from the passed in task. Its Swift signature is
Expand Down
19 changes: 19 additions & 0 deletions stdlib/public/Concurrency/Task.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,25 @@ bool swift::swift_task_isCancelled(AsyncTask *task) {
return task->isCancelled();
}

CancellationNotificationStatusRecord*
swift::swift_task_addCancellationHandler(
AsyncTask *task, CancellationNotificationStatusRecord::FunctionType handler) {
void *allocation =
swift_task_alloc(task, sizeof(CancellationNotificationStatusRecord));
auto *record =
new (allocation) CancellationNotificationStatusRecord(
handler, /*arg=*/nullptr);

swift_task_addStatusRecord(task, record);
return record;
}

void swift::swift_task_removeCancellationHandler(
AsyncTask *task, CancellationNotificationStatusRecord *record) {
swift_task_removeStatusRecord(task, record);
swift_task_dealloc(task, record);
}

SWIFT_CC(swift)
void swift::swift_continuation_logFailedCheck(const char *message) {
swift_reportError(0, message);
Expand Down
3 changes: 0 additions & 3 deletions stdlib/public/Concurrency/Task.swift
Original file line number Diff line number Diff line change
Expand Up @@ -585,9 +585,6 @@ func getJobFlags(_ task: Builtin.NativeObject) -> Task.JobFlags
@usableFromInline
func _enqueueJobGlobal(_ task: Builtin.Job)

@_silgen_name("swift_task_isCancelled")
func isTaskCancelled(_ task: Builtin.NativeObject) -> Bool
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we already have _taskIsCancelled, this was not used


@available(*, deprecated)
@_silgen_name("swift_task_runAndBlockThread")
public func runAsyncAndBlock(_ asyncFun: @escaping () async -> ())
Expand Down
29 changes: 25 additions & 4 deletions stdlib/public/Concurrency/TaskCancellation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,23 @@ extension Task {
///
/// Does not check for cancellation, and always executes the passed `operation`.
///
/// ### Suspension
/// This function returns instantly and will never suspend.
/* @instantaneous */
public static func withCancellationHandler<T>(
handler: @concurrent () -> (),
operation: () async throws -> T
) async throws -> T {
fatalError("\(#function) not implemented yet.")
) async rethrows -> T {
let task = Builtin.getCurrentAsyncTask()

guard !_taskIsCancelled(task) else {
// If the current task is already cancelled, run the handler immediately.
handler()
return try await operation()
}

let record = _taskAddCancellationHandler(task: task, handler: handler)
defer { _taskRemoveCancellationHandler(task: task, record: record) }

return try await operation()
}

/// The default cancellation thrown when a task is cancelled.
Expand All @@ -85,3 +94,15 @@ extension Task {
}

}

@_silgen_name("swift_task_addCancellationHandler")
func _taskAddCancellationHandler(
task: Builtin.NativeObject,
handler: @concurrent () -> ()
) -> UnsafeRawPointer /*CancellationNotificationStatusRecord*/

@_silgen_name("swift_task_removeCancellationHandler")
func _taskRemoveCancellationHandler(
task: Builtin.NativeObject,
record: UnsafeRawPointer /*CancellationNotificationStatusRecord*/
)
2 changes: 1 addition & 1 deletion test/Concurrency/async_cancellation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func test_cancellation_withCancellationHandler(_ anything: Any) async -> Picture
let handle: Task.Handle<PictureData, Error> = Task.runDetached {
let file = SomeFile()

return try await Task.withCancellationHandler(
return await Task.withCancellationHandler(
handler: { file.close() },
operation: {
await test_cancellation_guard_isCancelled(file)
Expand Down