Commit Graph

52 Commits

Author SHA1 Message Date
Konrad 'ktoso' Malawski
6872707574 [embedded][Concurrency] Further refine C-api boundary for isIsolating... 2025-04-29 22:29:26 +09:00
Konrad 'ktoso' Malawski
ea16df04ac [Concurrency] adjust how we fail creating an IsIsolatingCurrentContextDecision 2025-04-29 20:08:56 +09:00
Konrad 'ktoso' Malawski
e1dc854f8f [Concurrency] Change isIsolatingCurrent... to return Bool?
This changes the isIsolatingCurrentContext function to return `Bool?`
and removes all the witness table trickery we did previously to detect
if it was implemented or not. This comes at a cost of trying to invoke
it always, before `checkIsolated`, but it makes for an simpler
implementation and more checkable even by third party Swift code which
may want to ask this question.

Along with the `withSerialExecutor` function, this now enables us to
check the isolation at runtime when we have an `any Actor` e.g. from
`#isolation`.

Updates SE-0471 according to
https://forums.swift.org/t/se-0471-improved-custom-serialexecutor-isolation-checking-for-concurrency-runtime/78834/
review discussions
2025-04-29 20:08:55 +09:00
Konrad `ktoso` Malawski
e056c63c89 [Concurrency] Implement isIsolatingCurrentContext requirement and mode (#79788) 2025-03-11 09:48:38 +09:00
Alastair Houghton
f8d6012d9a Merge pull request #76483 from al45tair/eng/PR-135380149
[Concurrency] Build executors as their own separate object modules.
2024-10-02 09:39:46 +01:00
Michael Gottesman
cb8e8b505a Fix syntax highlighting by changing how we include COMPATIBILITY_OVERRIDE_INCLUDE_PATH.
The way that we include COMPATIBILITY_OVERRIDE_INCLUDE_PATH freaks out the
syntax highlighting of editors like emacs. It causes the whole file to be
highlighted like it is part of the include string.

To work around this, this patch creates a separate file called
CompatibilityOverrideIncludePath.h that just includes
COMPATIBILITY_OVERRIDE_INCLUDE_PATH. So its syntax highlighting is borked, but
at least in the actual files that contain real code, the syntax highlighting is
restored.
2024-10-01 16:17:16 -07:00
Alastair Houghton
e6882f243f [Concurrency] Fix Linux/Windows build issues.
Define `NOMINMAX` and `WIN32_LEAN_AND_MEAN` when including `<Windows.h>`.

Don't export the interface from DLLs.

Make sure we include `<new>` when using placement operator new.

rdar://135380149
2024-09-30 17:18:09 +01:00
Alastair Houghton
26b5fa697a [Concurrency] Rename ExecutorHooks.h, tidy up the interface.
`ExecutorHooks.h` is now nothing to do with hooks, so rename it.  Also
there are some additional functions it should declare, and a couple of
places where we've slightly messed up the boundary, for instance
`swift_task_asyncMainDrainQueue` was defined in `Task.cpp` rather than
in the executor implementations, which is wrong, so fix that too.

`CooperativeGlobalExecutor.cpp` now builds against the interface from
`ExecutorImpl.h`, rather than including the all the concurrency headers.

rdar://135380149
2024-09-30 17:15:40 +01:00
Alastair Houghton
efe5d660f2 [Concurrency] Refactor executors so they are in their own object module.
C++ executor implementations were `#include`ed into `GlobalExecutor.cpp`,
which makes it difficult to replace the global executor when using the
Embedded Concurrency library.  Refactor things so that they build into
separate objects, which means replacing them is just a matter of writing
the relevant functions yourself.

rdar://135380149
2024-09-30 17:15:38 +01:00
Konrad `ktoso` Malawski
2ec717b115 [Concurrency] TaskExecutor ownership fixes (#74000) 2024-06-14 22:56:33 +09:00
Yuta Saito
132ba8950b [Concurrency] Fix signature mismatch of _task_serialExecutor_checkIsolated
`_task_serialExecutor_checkIsolated` is defined as returning nothing in
`Executor.swift`, but it was used as returning a boolean in C++ side.
2024-03-31 04:48:50 +00:00
Konrad `ktoso` Malawski
86f5441294 [SerialExecutor] SerialExecutor.checkIsolated() to check its own tracking for isolation checks (#71172) 2024-03-29 07:06:34 +09:00
Allan Shortlidge
8343e7a292 NFC: Suppress -Wreturn-type-c-linkage warnings in GlobalExecutor.cpp. 2024-01-16 16:21:06 -08:00
Konrad `ktoso` Malawski
828f589be4 Initial Task Executor implementation Task(on:), addTask(on:) etc. (#68793)
Co-authored-by: John McCall <rjmccall@gmail.com>
2023-12-12 17:14:24 +09:00
Konrad `ktoso` Malawski
5546f4da7b Rename ExecutorRef to SerialExecutorRef 2023-11-01 18:39:44 +09:00
Konrad `ktoso` Malawski
0586c14b60 [Concurrency] SerialExecutor.isSameExclusiveExecutionContext (#64604) 2023-03-28 15:56:28 +09:00
Konrad `ktoso` Malawski
e0877594da [Concurrency] Custom executors with move-only Job (#63569) 2023-03-18 14:02:43 +09:00
Rokhini Prabhu
babaa4bc2a Merge pull request #63019 from apple/rokhinip/88093007-priority-escalation-to-future
Provide support for live priority escalation in the task runtime
2023-02-11 11:33:41 -08: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
Konrad `ktoso` Malawski
6b95ff7a25 [Concurrenncy] add internal way to assert we're on expected executor 2023-02-08 15:41:25 +09:00
Konrad `ktoso` Malawski
307ec5a378 [Concurrency] unownedExecutor can be declared not directly on actor 2023-02-08 13:38:02 +09:00
Josh Soref
7a57e7ce99 Spelling stdlib/public/concurrency (#42443)
* spelling: already

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: appropriate

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: asynchronous

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: cancel

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: divisible

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: execution

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: initialized

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: normally

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: preprocessed

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: priority

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: some

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: success

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: suspending

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: the

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: throws

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

Co-authored-by: Josh Soref <jsoref@users.noreply.github.com>
2022-04-21 11:12:57 -07: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
Mike Ash
0977920217 [Concurrency] Add tracing for major operations in the concurrency runtime.
Each trace point is declared as a function in the new `Tracing.h` header. These functions are called from the appropriate places in the concurrency runtime.

On Darwin, an implementation of these functions is provided which uses the `os/signpost.h` API to emit signpost events/intervals.

When the signpost API is not available, no-op stub implementations are provided. Implementations for other OSes can be provided by providing implementations of the trace functions for that OS.

rdar://81858487
2022-01-07 11:35:40 -05:00
John McCall
c45f2c4334 [NFC] Introduce a typedef for job delay in nanoseconds. 2021-11-16 01:50:52 -05:00
John McCall
0bd0f772d8 NFC: move the global executor implementations into their own files 2021-11-15 18:29:08 -05:00
Saleem Abdulrasool
701130a5ee Update GlobalExecutor.cpp (#39798)
Correct the conditional include for non-Apple targets.  This would previously always resolve to false.
2021-10-18 10:21:48 +09:00
Konrad `ktoso` Malawski
52bde17e3b [Concurrency] set queue width on all non-apple platforms, not just linux (#39764) 2021-10-16 15:33:07 +09:00
Konrad `ktoso` Malawski
8578d225f7 [Concurrency] Limit cooperative queue width with set_width on linux 2021-10-14 21:05:30 +09:00
John McCall
a76b304f00 Allow building a concurrent libSwiftConcurrency without libdispatch
The goal here is not to eventually implement a concurrent thread
pool ourselves.  We're just making it easier for integrators who
have their own pool and don't want to use Dispatch to build the
Swift concurrency runtime.  Just hook the right functions and
you should be fine.

The necessary functions to hook are:
- swift_task_enqueueGlobal
- swift_task_enqueueGlobalAfterDelay

The following functions *would* be necessary to hook:
- swift_task_enqueueMainExecutor
- swift_task_asyncMainDrainQueue (only if you have an async main?)
However, this configuration does not currently properly support
the main executor, and so `@MainActor` should be avoided for now.

rdar://83513751
2021-10-01 02:15:03 -04:00
Ben Langmuir
0e507f2f24 Revert "Allow building a concurrent libSwiftConcurrency without libdispatch" 2021-09-28 10:08:46 -07:00
John McCall
1df455bc14 Allow building a concurrent libSwiftConcurrency without libdispatch
The goal here is not to eventually implement a concurrent thread
pool ourselves.  We're just making it easier for integrators who
have their own pool and don't want to use Dispatch to build the
Swift concurrency runtime.  Just hook the right functions and
you should be fine.

The necessary functions to hook are:
- swift_task_enqueueGlobal
- swift_task_enqueueGlobalAfterDelay

The following functions *would* be necessary to hook:
- swift_task_enqueueMainExecutor
- swift_task_asyncMainDrainQueue (only if you have an async main?)
However, this configuration does not currently properly support
the main executor, and so `@MainActor` should be avoided for now.

rdar://83513751
2021-09-28 02:14:26 -04:00
Yuta Saito
5da91ff702 [Concurrency] repair cooperative main executor
This patch repairs the build failure for cooperative executor.
And also fixed main executor to avoid assertion failure due to
`witnessTable == nullptr`
2021-09-19 12:47:07 +00:00
Doug Gregor
136a40aaad Use private concurrent queues for back-deployed concurrency.
Older Dispatch versions have width-limited concurrent queues. While not
as good as the newly-introduced cooperative queues, they at least
address the thread-explosion problem, so use them in the back-deployed
concurrency libraries.

Implements rdar://81131034.
2021-09-13 15:20:06 -07:00
Doug Gregor
d844d0b82b Merge pull request #39102 from DougGregor/back-deploy-standalone
Make the back-deployed concurrency dylibs depend only on what's available in older runtimes
2021-08-31 09:05:21 -07:00
Yuta Saito
f6f756e851 [Concurrency] repair cooperative global executor (#39092)
`SWIFT_STDLIB_SINGLE_THREADED_RUNTIME` mode has been broken for a long time.

This patch guards some includes and use of libdispatch headers so that platforms
that doesn't support libdispatch can build cooperative executor runtime.
And fixed missing implementations for cooperative mode.
2021-08-31 09:31:50 +01:00
Doug Gregor
2fe8d03599 Disable job-based dispatch integration in the back-deployed library. 2021-08-30 11:36:16 -07:00
Julian Lettner
558a0cc605 Add tsan_release edge on task creation (#38074)
* Synchronize both versions of actor_counters.swift test

* Synchronize on Job address

Make sure to synchronize on Job address (AsyncTasks are Jobs, but not
all Jobs are AsyncTasks).

* Add fprintf debug output for TSan acquire/release

* Add tsan_release edge on task creation

without this, we are getting false data races between when a task
is created and immediately scheduled on a different thread.

False positive for `Sanitizers/tsan/actor_counters.swift` test:
```
WARNING: ThreadSanitizer: data race (pid=81452)
  Read of size 8 at 0x7b2000000560 by thread T5:
    #0 Counter.next() <null>:2 (a.out:x86_64+0x1000047f8)
    #1 (1) suspend resume partial function for worker(identity:counters:numIterations:) <null>:2 (a.out:x86_64+0x100005961)
    #2 swift::runJobInEstablishedExecutorContext(swift::Job*) <null>:2 (libswift_Concurrency.dylib:x86_64+0x280ef)

  Previous write of size 8 at 0x7b2000000560 by main thread:
    #0 Counter.init(maxCount:) <null>:2 (a.out:x86_64+0x1000046af)
    #1 Counter.__allocating_init(maxCount:) <null>:2 (a.out:x86_64+0x100004619)
    #2 runTest(numCounters:numWorkers:numIterations:) <null>:2 (a.out:x86_64+0x100006d2e)
    #3 swift::runJobInEstablishedExecutorContext(swift::Job*) <null>:2 (libswift_Concurrency.dylib:x86_64+0x280ef)
    #4 main <null>:2 (a.out:x86_64+0x10000a175)
```

New edge with this change:
```
[4357150208] allocate task 0x7b3800000000, parent = 0x0
[4357150208] creating task 0x7b3800000000 with parent 0x0
[4357150208] tsan_release on 0x7b3800000000    <<< new release edge
[139088221442048] tsan_acquire on 0x7b3800000000
[139088221442048] trying to switch from executor 0x0 to 0x7ff85e2d9a00
[139088221442048] switch failed, task 0x7b3800000000 enqueued on executor 0x7ff85e2d9a00
[139088221442048] enqueue job 0x7b3800000000 on executor 0x7ff85e2d9a00
[139088221442048] tsan_release on 0x7b3800000000
[139088221442048] tsan_release on 0x7b3800000000
[4357150208] tsan_acquire on 0x7b3800000000
counters: 1, workers: 1, iterations: 1
[4357150208] allocate task 0x7b3c00000000, parent = 0x0
[4357150208] creating task 0x7b3c00000000 with parent 0x0
[4357150208] tsan_release on 0x7b3c00000000    <<< new release edge
[139088221442048] tsan_acquire on 0x7b3c00000000
[4357150208] task 0x7b3800000000 waiting on task 0x7b3c00000000, going to sleep
[4357150208] tsan_release on 0x7b3800000000
[4357150208] tsan_release on 0x7b3800000000
[139088221442048] getting current executor 0x0
[139088221442048] tsan_release on 0x7b3c00000000
...
```

rdar://78932849

* Add static_cast<Job *>()

* Move TSan release edge to swift_task_enqueueGlobal()

Move the TSan release edge from `swift_task_create_commonImpl()` to
`swift_task_enqueueGlobalImpl()`.  Task creation itself is not an event
that needs synchronization, but rather that task creation "happens
before" execution of that task on another thread.

This edge is usually added when the task is scheduled via
`swift_task_enqueue()` (which then usually calls
`swift_task_enqueueGlobal()`).  However, not all task scheduling goes
through the `swift_task_enqueue()` funnel as some places call the more
specific `swift_task_enqueueGlobal()` directly.  So let's annotate this
function (duplicate edges aren't harmful) to ensure we cover all
schedule events, including newly-created tasks (our original problem
here).

rdar://78932849

Co-authored-by: Julian Lettner <julian.lettner@apple.com>
2021-06-25 18:40:53 -07:00
John McCall
ca62a79079 Use &_dispatch_main_q as the identity of the main actor.
I added Builtin.buildMainActorExecutor before, but because I never
implemented it correctly in IRGen, it's not okay to use it on old
versions, so I had to introduce a new feature only for it.

The shim dispatch queue class in the Concurrency runtime is rather
awful, but I couldn't think of a reasonable alternative without
just entirely hard-coding the witness table in the runtime.
It's not ABI, at least.
2021-06-17 05:04:30 -04:00
Mike Ash
70be680e94 [Concurrency] Fix the call to swift_task_enqueueGlobal_hook.
We pass swift_task_enqueueGlobal as the original implementation, but that would recurse. We need to pass swift_task_enqueueGlobalImpl instead.

rdar://78780136
2021-06-02 16:46:31 -04:00
Yuta Saito
709359cfab Rename duplicated swift::fatalError definition in swiftRuntime and swift_Concurrency
Both swiftRuntime and swift_Concurrency had swift::fatalError
implementation, but it causes symbol conflict when -static-stdlib.

This patch renames one of the impl in swift_Concurrency to avoid
conflict.
2021-04-28 23:52:18 +09:00
Mike Ash
2dc06c5fe2 [Concurrency] Fix Dispatch linkage offset on 32-bit.
rdar://76703675
2021-04-15 12:18:38 -04:00
Mike Ash
e98fc3e304 Merge pull request #36572 from mikeash/async-task-dispatch-integration2
[Concurrency] Make Job objects work as Dispatch objects.
2021-03-31 09:42:58 -04:00
Mike Ash
0989524338 [Concurrency] Make Job objects work as Dispatch objects.
Fill out the metadata for Job to have a Dispatch-compatible vtable. When available, use the dispatch_enqueue_onto_queue_4Swift to enqueue Jobs directly onto queues. Otherwise, keep using dispatch_async_f as we have been.

rdar://75227953
2021-03-26 18:31:00 -04:00
Mike Ash
6aab257c33 [Concurrency] Add compatibility overrides to Concurrency library.
Take the existing CompatibilityOverride mechanism and generalize it so it can be used in both the runtime and Concurrency libraries. The mechanism is preprocessor-heavy, so this requires some tricks. Use the SWIFT_TARGET_LIBRARY_NAME define to distinguish the libraries, and use a different .def file and mach-o section name accordingly.

We want the global/main executor functions to be a little more flexible. Instead of using the override mechanism, we expose function pointers that can be set by the compatibility library, or by any other code that wants to use a custom implementation.

rdar://73726764
2021-03-22 11:09:06 -04:00
Mike Ash
bd62fdb2db [Concurrency] Make Job/AsyncTask minimally compatible with dispatch object layout
Create a TargetDispatchClassMetadata for Swift metadata that also has a dispatch-compatible vtable. Dispatch leaves room for ObjC class metadata so the two regions don't overlap. (The vtable currently consists of a single dummy entry; this will be filled out later.)

Rearrange the Job and AsyncTask hierarchy so that AsyncTask inherits only from Job, which in turn inherits from HeapObject. This gives all Job instances a dispatch-compatible isa field. It also gives them a refcount word, which is wasted on instances that aren't AsyncTask instances. Maybe we can find some use for that space in the future.

rdar://75227953
2021-03-10 10:04:30 -05:00
Mike Ash
01f1a2dfb1 [Concurrency] Cache the queue returned from dispatch_get_global_queue.
We'll be using these queues a lot, so avoid calling that function every single time.

rdar://70578614
2021-03-05 10:19:22 -05:00
Dario Rexin
af4b6bc068 [Concurrency] Add asynchronous Task.sleep function 2021-03-04 09:37:58 -08:00
John McCall
8e9823c369 Store the current task and executor in task-local storage. 2021-02-21 21:39:14 -05:00
Kavon Farvardin
91e2246c19 quick-and-dirty implementation of MainActor in the runtime system
it is "dirty" in the sense that we don't have proper support for
custom executors right now.
2021-01-14 17:43:58 -08:00