Commit Graph

237 Commits

Author SHA1 Message Date
Konrad `ktoso` Malawski
11b6bd0396 better example 2023-09-12 21:34:50 +09:00
Konrad `ktoso` Malawski
1e7e5181ab Document more explicitly closure lifetime of a Task init 2023-09-12 21:02:28 +09:00
Yuta Saito
97ac3985e2 [Concurrency] Fix signature mismatch of _startTaskOnMainActor
The function is defined in Task.cpp with a void return type, but
referenced in Task.swift with an pointer return type.
2023-06-11 12:29:11 +00:00
Konrad `ktoso` Malawski
d82de55ae4 less code duplication 2023-05-24 18:46:57 +02:00
Konrad `ktoso` Malawski
cad608eb81 [Discarding] Don't leak retained "first error" task when retaining it 2023-05-24 18:03:28 +02:00
Evan Wilde
ad81f8d557 Allow discarding startOnMainActor results
Adding discardableResult to startOnMainActor
2023-04-18 16:40:54 -07:00
Kavon Farvardin
f40d90f885 fix another unguarded use of MainActor 2023-03-08 14:12:13 -08:00
Evan Wilde
f8e1272097 Concurrency: appease the api-digester
Looks like simply putting the availability attribute on the extension
does not suffice. Putting the availability attr on the function itself
to appease the api-digester.
2023-03-06 13:33:22 -08:00
Evan Wilde
1bd1c468a0 Concurrency: Task.startOnMainActor
This patch adds an SPI to run the first partial function of a MainActor
asynchronous function on the MainActor synchronously. This is
effectively like the asynchronous program entrypoint behavior. The first
partial function is run synchronously. Following continuations are
enqueued for execution like any other asynchronous function.
2023-03-06 13:33:22 -08:00
Konrad `ktoso` Malawski
a2783b2e8d [Concurrency] UnownedJob.priority and description for TaskPriority 2023-02-28 16:17:48 +09:00
Konrad `ktoso` Malawski
5431c6dad3 [Concurrency] Base priority should be present on UnsafeTask too (#63563) 2023-02-22 15:56:50 +09:00
Rokhini Prabhu
e052ccef31 Create the notion of a TaskDependencyStatusRecord which tracks what a
task is blocked on. We can use this information to then perform live
priority escalation to a task future.

Radar-Id: rdar://problem/88093007
2023-02-08 17:29:55 -08:00
Nate Chandler
c574550073 [Freestanding] Removed bridging intrinsic. 2022-10-18 11:27:21 -07:00
Nate Chandler
34c08b8344 [TaskToThread] Add Task.runInline.
The new intrinsic, exposed via static functions on Task<T, Never> and
Task<T, Error> (rethrowing), begins an asynchronous context within a
synchronous caller's context.  This is only available for use under the
task-to-thread concurrency model, and even then only under SPI.
2022-07-08 08:44:18 -07:00
Nate Chandler
68eea8adec [TaskToThread] No unstructured tasks.
In this mode, the following are disabled:

- task creation
- global actors
- MainActor
- custom executors
2022-07-06 11:51:16 -07:00
Evan Wilde
9ab7a822df Cleaning up _runAsyncMain a bit
I'm making two cleanups here. First, the closure going into
`_runAsyncMain` needs to be `@Sendable` or passing it to the task is not
safe. This will also result in a warning being emitted.
Second, I'm making this @usableFromInline and `internal`. This function
is around for legacy reasons, but it's part of the ABI, so we can't pull
it out entirely, but we don't want folks using it.
2022-03-21 13:02:20 -07:00
Hamish Knight
a2cfbda850 Revert "Cleaning up _runAsyncMain a bit" 2022-03-05 13:14:36 +00:00
Evan Wilde
b6414b383b Merge branch 'main' into ewilde/concurrency/cleanup-run-async-main 2022-02-17 16:08:17 -08:00
Philippe Hausler
e675b310f8 [SE-0329] Clock/Instant/Duration (#40609)
* [WIP] Initial draft at v2 Clock/Instant/Duration

* Ensure the literal types for _DoubleWide are able to be at least 64 bits on 32 bit platforms

* static cast timespec members to long

* Remove runtime exports from clock functions

* Export clock functions in implementations as they are in headers

* Clean up internal properties by adding leading underscores, refine availability to a TBD marker macro, and break at 80 lines to match style

* Shift operators to concrete Instant types to avoid complexity in solver resolution

* Adjust diagnostic note and error expectation of ambiguities to reflect new potential solver (perhaps incorrect) solutions

* Update stdlib/public/Concurrency/TaskSleep.swift

Co-authored-by: Karoy Lorentey <klorentey@apple.com>

* [stdlib][NFC] Remove trailing whitespace

* [stdlib] Remove _DoubleWidth from stdlib's ABI

* [stdlib] Strip downd _DoubleWidth to _[U]Int128

* Additional adjustments to diagnostic notes and errors expectation of ambiguities to reflect new potential solver (perhaps incorrect) solutions

* Disable type checker performance validation for operator overload inferences (rdar://33958047)

* Decorate Duration, DurationProtocol, Instant and clocks with @available(SwiftStdlib 9999, *)

* Restore diagnostic ambiguity test assertion (due to availability)

* Add a rough attempt at implementing time accessors on win32

* Remove unused clock id, rename SPI for swift clock ids and correct a few more missing availabilities

* remove obsolete case of realtime clock for dispatch after callout

* Use the default implementation of ~ for Int128 and UInt128

* Ensure diagnostic ambiguitiy applies evenly to all platforms and their resolved types

* Restore the simd vector build modifications (merge damage)

* Update to latest naming results for Instant.Duration

* Updates to latest proposal initializers and accessors and adjust encoding/decoding to string based serialization

* Update availability for Clock/Instant/Duration methods and types to be 5.7

* Correct *Clock.now to report via the correct runtime API

* Ensure the hashing of Duration is based upon the attoseconds hashing

* Avoid string based encoding and resort back to high and low bit encoding/decoding but as unkeyed

* Adjust naming of component initializer to use suffixes on parameters

* Duration decoding should use a mutable container for decoding

* fix up components initializer and decode access

* Add platform base initializers for timespec and tiemval to and from Duration

* Add some first draft documentation for standard library types Duration, DurationProtocol and InstantProtocol

* Another round of documentation prose and some drive-by availability fixes

* InstantProtocol availability should be 5.7

* Correct linux timeval creation to be Int and not Int32

Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2022-02-17 09:32:46 -08:00
Konrad `ktoso` Malawski
083afff45a Update stdlib/public/Concurrency/Task.swift
Co-authored-by: Alex Martini <amartini@apple.com>
2022-02-10 10:54:16 +09:00
Konrad `ktoso` Malawski
6691dcff81 Update stdlib/public/Concurrency/Task.swift
Co-authored-by: Kavon Farvardin <kfarvardin@apple.com>
2022-02-04 06:57:19 +09:00
Konrad `ktoso` Malawski
259c37c4ca [Concurrency] Fix docs which suggested outdated patterns; can't store "current" task safely 2022-02-03 20:57:37 +09:00
Ole Begemann
b32ae80e0c Remove Task.CancellationError in doc comments
Task.CancellationError has been renamed to CancellationError. Fix two doc comments that still used the old name.
2022-01-30 20:17:36 +01:00
Karoy Lorentey
61268aa259 [stdlib] Define placeholder version numbers for SwiftStdlib 5.7
Also update existing declarations with SwiftStdlib 9999 availability to use the 5.7 name.
2022-01-27 14:41:07 -08:00
Rokhini Prabhu
9df1c9a135 Track base priority separately from max priority whereby base priority
is set at creation time. Create a new API for accessing this state

Radar-Id: rdar://problem/86100376
2022-01-24 07:50:27 -08:00
Rokhini Prabhu
8f2ac188fb Make sure that currentPriority actually reads the max QoS in the active
task status instead of the Job priority which is not necessarily in sync

Radar-Id: rdar://problem/86100376
2022-01-21 12:12:12 -08:00
Evan Wilde
bfcc809ac8 Merge branch 'main' into ewilde/concurrency/cleanup-run-async-main 2022-01-03 08:36:40 -08:00
Evan Wilde
1f198bcd93 Cleaning up _runAsyncMain a bit
I'm making two cleanups here. First, the closure going into
`_runAsyncMain` needs to be `@Sendable` or passing it to the task is not
safe. This will also result in a warning being emitted.
Second, I'm making this @usableFromInline and `internal`. This function
is around for legacy reasons, but it's part of the ABI, so we can't pull
it out entirely, but we don't want folks using it.
2021-12-21 11:42:09 -08:00
Doug Gregor
c4e8844fdb Merge pull request #40616 from DougGregor/concurrency-sendable-frozen-types 2021-12-17 16:47:40 -08:00
Doug Gregor
400404cf3a Explicit Sendable conformances for @frozen types
Task groups and `UnsafeCurrentTask` are non-`Sendable`.
`UnownedSerialExecutor` is always `Sendable`.

Fixes rdar://86496341.
2021-12-17 11:10:29 -08:00
najacque
57ad1f1c7d Merge pull request #40115 from amartini51/concurrency_docs_to_main
Cherry-pick concurrency docs
2021-12-07 11:59:56 -08:00
swift-ci
37ea254cc1 Merge pull request #40220 from DougGregor/predates-concurrency 2021-11-19 01:14:42 -08:00
Doug Gregor
089cc4f101 Remove last use of @_unsafeSendable in the concurrency library 2021-11-18 11:20:53 -08:00
Evan Wilde
1c852f9179 Adding @usableFromInline to needed API
getMainExecutor and asyncMainDrainQueue function declarations are needed
to compile programs with the asyn-main function. The functions are
declared internal, so they don't show up in the swift interface files.
2021-11-16 21:36:58 -08:00
Alex Martini
0f75fc7f51 Cherry pick Swift 5.5 doc changes in Task.swift 2021-11-09 17:23:38 -08:00
Karoy Lorentey
47956908b7 [Concurrency] SwiftStdlib 5.5 ⟹ SwiftStdlib 5.1 (usages)
The concurrency runtime now deploys back to macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, which corresponds to the 5.1 release of the stdlib.

Adjust macro usages accordingly.
2021-10-28 14:36:36 -07:00
Doug Gregor
19e3f640f7 Drop unintended @_transparent. 2021-10-13 11:44:20 -07:00
Doug Gregor
c8315682db Make sure that Task.isCancelled fix works on older OSs.
Part of rdar://84146091 & SR-15309.
2021-10-13 10:25:04 -07:00
Evan Wilde
d376ee9989 Run first thunk of Async main synchronously
This patch updates the asynchronous main function to run the first thunk
of the function synchronously through a call to `swift_job_run`.

The runloop is killed by exiting or aborting the task that it is running
on. As such, we need to ensure that the task contains an async function
that either calls exit explicitly or aborts. The AsyncEntryPoint, that
contains this code, was added in the previous patch. This patch adds the
pieces for the actual implementation of this behaviour as well as adding
the necessary code to start the runloop.

There are now four layers of main functions before hitting the "real"
code.

@main: This is the actual main entrypoint of the program. This
constructs the task containing @async_main, grabs the main executor,
runs swift_job_run to run the first part synchronously, and finally
kicks off the runloop with a call to _asyncMainDrainQueue. This is
generated in the call to `emitAsyncMainThreadStart`.

@async_main: This thunk exists to ensure that the main function calls
`exit` at some point so that the runloop stops. It also handles emitting
an error if the user-written main function throws.

e.g:

```
func async_main() async -> () {
  do {
    try await Main.$main()
    exit(0)
  } catch {
    _errorInMain(error)
  }
}
```

Main.$main(): This still has the same behaviour as with the
synchronous case. It just calls `try await Main.main()` and exists to
simplify typechecking.

Main.main(): This is the actual user-specified main. It serves the same
purpose as in the synchronous, allowing the programmer to write code,
but it's async!

The control flow in `emitFunctionDefinition` is a little confusing (to
me anyway), so here it is spelled out:

If the main function is synchronous, the `constant.kind` will be a
`SILDeclRef::Kind::EntryPoint`, but the `decl` won't be async, so it
drops down to `emitArtificalTopLevel` anyway.

If the main function is async and we're generating `@main`, the
`constant.kind` will be `SILDeclRef::Kind::AsyncEntryPoint`, so we also
call `emitArtificalTopLevel`. `emitArtificalTopLevel` is responsible for
detecting whether the decl is async and deciding whether to emit code to
extract the argc/argv variables that get passed into the actual main
entrypoint to the program. If we're generating the `@async_main` body,
the kind will be `SILDeclRef::Kind::EntryPoint` and the `decl` will be
async, so we grab the mainEntryPoint decl and call
`emitAsyncMainThreadStart` to generate the wrapping code.

Note; there is a curious change in `SILLocation::getSourceLoc()`
where instead of simply checking `isFilenameAndLocation()`, I change it
to `getStorageKind() == FilenameAndLocationKind`. This is because the
SILLocation returned is to a FilenameAndLocationKind, but the actual
storage returns true for the call to `isNull()` inside of the
`isFilenameAndLocation()` call. This results in us incorrectly falling
through to the `getASTNode()` call below that, which asserts when asked
to get the AST node of a location.

I also did a little bit of refactoring in the SILGenModule for grabbing
intrinsics. Previously, there was only a `getConcurrencyIntrinsic`
function, which would only load FuncDecls out of the concurrency
module. The `exit` function is in the concurrency shims module, so I
refactored the load code to take a ModuleDecl to search from.

The emitBuiltinCreateAsyncTask function symbol is exposed from
SILGenBuiltin so that it is available from SILGenFunction. There is a
fair bit of work involved going from what is available at the SGF to
what is needed for actually calling the CreateAsyncTask builtin, so in
order to avoid additional maintenance, it's good to re-use that.
2021-10-02 16:53:06 -07:00
Doug Gregor
95d84d6581 Allow a Swift 5.5 compiler to process the new _Concurrency module.
Swift 5.5 does not implement support for structural types that are
Sendable, which breaks type checking of the newer _Concurrency module.
Work around the issue with an `#if` in the offending inline code.

Fixes rdar://82602353.
2021-09-02 12:22:32 -07:00
Doug Gregor
4a63884026 Add missing Sendable requirements and a conformance 2021-08-26 10:56:48 -07:00
Doug Gregor
3723c2f685 Adopt Sendable in the Task APIs 2021-08-14 08:13:10 -07:00
Doug Gregor
d9e3259ff6 [SE-0304] Clean up handling of task priorities. 2021-07-30 12:53:03 -07:00
Doug Gregor
8884e3a510 [SE-0304] Rename Task.suspend() back to Task.yield(). 2021-07-27 12:19:55 -07:00
Andrew Trick
982b47d829 Add Builtin.hopToActor to the feature list.
This builtin never occurs in @inlinable code. But apparently we still
need to add a language feature for every builtin. This must allow
older compilers to reparse the library source (though I don't know why
that would ever happen!)

Fixes rdar://80525569 error: module 'Builtin' has no member named 'hopToActor')
2021-07-13 16:28:38 -07:00
Doug Gregor
4a0723f68c [SE-0304] Add UnsafeCurrentTask.cancel(). 2021-07-08 13:22:33 -07:00
Doug Gregor
59d1e61ac4 [SE-0304] Implement cancellable Task.sleep(nanoseconds:). 2021-07-08 09:46:07 -07:00
Doug Gregor
b7e2136e4a [SE-0304] Rename Task.yield() to Task.suspend() 2021-07-07 20:30:57 -07:00
Doug Gregor
f692faea6a [SE-0304] Rename TaskPriority.default to medium 2021-07-07 18:06:52 -07:00
Doug Gregor
819615eab1 Make Swift task-creation entry points always-emit-into-client.
The `swift_task_create` entry point is our general runtime ABI for
launching tasks. Make the various Swift APIs sitting on top of it
always-emit-into-client to take them out of the ABI. This reduces the
number of ABI entry points and allows us to make more ABI-compatible
changes to the Swift side.
2021-06-24 07:53:19 -07:00