Concurrency

RSS for tag

Concurrency is the notion of multiple things happening at the same time.

Posts under Concurrency tag

93 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Concurrency Resources
Swift Concurrency Resources: DevForums tags: Concurrency The Swift Programming Language Concurrency > Concurrency documentation WWDC 2022 Session 110351 Eliminate data races using Swift Concurrency — This ‘sailing on the sea of concurrency’ talk is a great introduction to the fundamentals. WWDC 2021 Session 10134 Explore structured concurrency in Swift — The table that starts rolling out at around 25:45 is really helpful. Dispatch Resources: DevForums tags: Dispatch Dispatch documentation — Note that the Swift API and C API, while generally aligned, are different in many details. Make sure you select the right language at the top of the page. Dispatch man pages — While the standard Dispatch documentation is good, you can still find some great tidbits in the man pages. See Reading UNIX Manual Pages. Start by reading dispatch in section 3. WWDC 2015 Session 718 Building Responsive and Efficient Apps with GCD [1] WWDC 2017 Session 706 Modernizing Grand Central Dispatch Usage [1] Avoid Dispatch Global Concurrent Queues DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" [1] These videos may or may not be available from Apple. If not, the URL should help you locate other sources of this info.
0
0
591
Nov ’23
CommandGroup, Xcode 16b1, and Swift 6
I suspect this will be a "wait for the next beta" item, but thought I'd throw it out here in case anyone knows of a workaround. Mac app compiling under Xcode 16 beta 1. Trying to get rid of all warning that would stop the adoption of Swift 6 -- Strict Concurrency Checking is set to Complete. I'm down to one warning before I can enable swift 6. SwiftUI.Commands Main actor-isolated static method '_makeCommands(content:inputs:)' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode That's because I've added menu commands to the app. It's very easy to reproduce. import SwiftUI @main struct CommandApp: App { var body: some Scene { WindowGroup { ContentView() } .commands { HelpCommand() } } } struct HelpCommand: Commands { var body: some Commands { CommandGroup(replacing: .help) { Button("Help me") { // } } } } The suggested fix is telling me what change I should make ot _makeCommands. At least that is how I'm reading it.
0
0
14
1h
Metal and Swift Concurrency
Hi, Introducing Swift Concurrency to my Metal app has been a bit challenging as Swift Concurrency is limited by the cooperative thread pool. GPU work is obviously not CPU bound and can block forward moving progress, especially when using waitUntilCompleted on the command buffer. For concurrent render work this has the potential of under utilizing the CPU and even creating dead locks. My question is, what is the Metal's teams general recommendation when it comes to concurrency? It seems to me that Dispatch or OperationQueues are still the preferred way for Metal bound tasks in order to gain maximum performance? To integrate with Swift Concurrency my idea is to use continuations that kick off render jobs via Dispatch or Queues? Would this be the best solution to bridge async tasks with Metal work? Thanks!
4
0
79
9h
Crash objc_retain_x0
Attaching several crash traces: 2024-02-29_22-48-33.6864_-0600-3f948243e21b4c68d77a38d9cf1cecfdfe2c1565.crash 2024-03-04_15-00-02.9335_-0600-75000cd5acd63ba1434f2ffb3648b97259dddb88.crash 2024-03-05_08-55-47.2097_-0500-f682b25663107ad46f091d65f402f2be31f3f3c6.crash 2024-03-11_08-09-00.4057_-0400-e37d1a635d51afbb67ac38b42dd79c1718a408e8.crash 2024-03-15_16-20-22.6446_-0600-d4ebccf455e8305038ca564a39a5661a1dce6231.crash The final code: - (NSObject*)objectAtIndex:(NSUInteger)index { if (index < self.count) { return [self.embeddedArray objectAtIndex:index]; } else { [PNDErrorReporting reportError:PNDErrorReasonTypeSafeCollectionCrashPrevented message:@"Error msg"]; return nil; } } We subclass NSMutableArray to prevent potential crashes. but we encounter a new crash in our sdk for one of the clients. Also we noticed the stack trace skipped one of the frames (stack calls) in the crash report, in which cases the stack trace wont be identical to the actual code (beside inline)?
8
0
115
14h
Offloading task from the cooperative thread pool
Hi, When using Swift Concurrency blocking tasks like file I/O, GPU work and networking can prevent forward moving progress and have the potential to exhaust the cooperative thread pool and under utilize the CPU. It's been recommended to offload these tasks from the cooperative thread pool. Is my understanding correct that the preferred way to do this is by creating async tasks via Dispatch or OperationQueue? And combining these with Continuations if a return value from the task is required? Or should I always be using Continuations in combination with Dispatch/OperationQueue? There are also Executors but the documentation seems a bit limited on how to use these. The new TaskExecutor is also only available on the latest beta's. My question is basically what is the recommend way to offload a task? Thanks!
0
0
41
15h
SwiftUI Shape concurrency warnings
How are SwiftUI Shapes supposed to work with Swift 6? Shape conforms to View which uses @MainActor but the path function and animatableData are both nonisolated. How can they access animatable properties that have to be a var on the main actor? Below is a simple Shape that will show these warnings: struct SimpleShape: Shape { var width: Double var animatableData: Double { get { width } set { width = newValue } } func path(in rect: CGRect) -> Path { var path = Path() let width = self.width path.addRect(.init(origin: rect.origin, size: .init(width: width, height: rect.height))) return path } }
2
0
160
1d
Fix actor-isolated class is different from nonisolated subclass error
I'm trying to migrate my fairly large application to Swift Concurrency. I've have a class marked as @MainActor that sub-classes a 3rd party abstract class that is not migrated to Swift Concurrency. I get the following error: Main actor-isolated class 'MyClass' has different actor isolation from nonisolated superclass 'OtherAbstractClass'; this is an error in the Swift 6 language mode My class needs to be MainActor as it uses other code that is required to be on the MainActor. I can't see how to suppress this warning, I know as a guarantee that the abstract class will always be on the main thread so I need a way of telling the compiler that when I don't own the 3rd party code. import OtherAbstractModule @MainActor class MyClass: OtherAbstractClass { .... } How can I satisfy the compiler in this case?
1
0
91
1d
How to avoid Swift 6 concurrency warning from UIAccessibility.post()
I have the following var in an @Observable class: var displayResult: String { if let currentResult = currentResult, let decimalResult = Decimal(string: currentResult) { let result = decimalResult.formatForDisplay() UIAccessibility.post(notification: .announcement, argument: "Current result \(result)") return result } else { return "0" } } The UIAccessiblity.post gives me this warning: Reference to static property 'announcement' is not concurrency-safe because it involves shared mutable state; this is an error in Swift 6 How can I avoid this?
2
0
78
1d
Using Core Data with the Swift 6 language mode
I'm starting to work on updating my code for Swift 6. I have a number of pieces of code that look like this: private func updateModel() async throws { try await context.perform { [weak self] in // do some work } } After turning on strict concurrency checking, I get warnings on blocks like that saying "Sending 'self.context' risks causing data races; this is an error in the Swift 6 language mode." What's the best way for me to update this Core Data code to work with Swift 6?
2
0
177
1d
UIDevice: Main actor-isolated class property 'current' can not be referenced from a non-isolated context
I have a Safari Web Extension for visionOS that reads from UIDevice.current.systemVersion in order to provide the OS version number back to the JavaScript context utilizing beginRequest(with:). When switching my project to use Swift 6, I received this obscure error: Main actor-isolated class property 'current' can not be referenced from a non-isolated context Class property declared here (UIKit.UIDevice) Add '@MainActor' to make instance method 'beginRequest(with:)' part of global actor 'MainActor' Adding @MainActor causes another issue (Main actor-isolated instance method 'beginRequest(with:)' cannot be used to satisfy nonisolated protocol requirement) which suggests adding @preconcurrency to NSExtensionRequestHandling which then breaks at Non-sendable type 'NSExtensionContext' in parameter of the protocol requirement satisfied by main actor-isolated instance method 'beginRequest(with:)' cannot cross actor boundary. What's the proper solution here? Here's a simplified snippet of my code: class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { // ... var systemVersionNumber = "" systemVersionNumber = UIDevice.current.systemVersion // ... } }
1
0
142
1d
SwiftData SchemaMigrationPlan and VersionedSchema not Sendable?
I've just tried to update a project that uses SwiftData to Swift 6 using Xcode 16 beta 1, and it's not working due to missing Sendable conformance on a couple of types (MigrationStage and Schema.Version): struct LocationsMigrationPlan: SchemaMigrationPlan { static let schemas: [VersionedSchema.Type] = [LocationsVersionedSchema.self] static let stages: [MigrationStage] = [] } struct LocationsVersionedSchema: VersionedSchema { static let models: [any PersistentModel.Type] = [ Location.self ] static let versionIdentifier = Schema.Version(1, 0, 0) } This code results in the following errors: error: static property 'stages' is not concurrency-safe because non-'Sendable' type '[MigrationStage]' may have shared mutable state static let stages: [MigrationStage] = [] ^ error: static property 'versionIdentifier' is not concurrency-safe because non-'Sendable' type 'Schema.Version' may have shared mutable state static let versionIdentifier = Schema.Version(1, 0, 0) ^ Am I missing something, or is this a bug in the current seed? I've filed this as FB13862584.
1
0
84
1d
Why isn't the View protocol @MainActor?
Hi, It is known that if a SwiftUI view contains an @ObservedObject or @StateObject property, the View will inherit @MainActor isolation from the property wrappers. Similarly, the body view-builder is also marked @MainActor. What I'm wondering is why the whole SwiftUI View protocol isn't marked @MainActor. It seems to be a deliberate decision, but AFAICT it would make a lot of sense for all data and operations defined in a view to have main-actor isolation unless marked nonisolated. I'm currently adding @MainActor annotations to an existing codebase, and it's a bit awkward that some views automatically gain this attribute one way or another, while others need it explicitly applied. Is there a rationale that can be shared, or is this something which may be revised in future versions of the framework?
1
6
1.2k
3d
Function called isolated on MainActor via an isolated parameter are not considered run on the MainActor
If I try to compile the following, I get a compilation error: import Foundation func isolatedPrint<A : Actor>(on actor: isolated A) { print("hello") } Task{ @MainActor in isolatedPrint(on: MainActor.shared) } The error: toto.swift:9:2: error: expression is 'async' but is not marked with 'await' isolatedPrint(on: MainActor.shared) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ await toto.swift:9:2: note: calls to global function 'isolatedPrint(on:)' from outside of its actor context are implicitly asynchronous isolatedPrint(on: MainActor.shared) ^ I don’t understand why the compiler does not detect the function is called on the MainActor via the actor parameter.
1
0
211
1w
Ensuring exclusive access to a function in structured concurrency
So our back end manages tokens in a strange way. Whenever we try to request a new access token using our refresh token, it invalidates our old refresh token and returns us with a new access + refresh token. The problem with this is that multiple concurrent network requests can see that a user's access token has expired and try to get a new access token, potentially causing us to get a 401 unauthorized error. Is there any way with structured/unstructured concurrency to ensure that our method for grabbing the access token can only at max be run once at a time? Im assuming the only realistic way would be to do something like this: @MyGlobalActor private var tokenTask: Task<String, any Error>? @MyGlobalActor func getAccessToken() async await -> String { if let tokenTask { return try await tokenTask.value } self.tokenTask = Task<String, any Error> { // refresh access token } let token = try await self.tokenTask!.value self.tokenTask = nil return token }
1
0
178
1w
Migrating @MainActor ViewModel to @Observable causing error
I get this error while migrating from ObservableObject to @Observable. Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context My original code: struct SomeView: View { @StateObject private var viewModel = ViewModel() } After migration: @MainActor @Observable class BaseViewModel { } @MainActor class ViewModel: BaseViewModel { } struct SomeView: View { @State private var viewModel = ViewModel() } As discussed here. It seems like @StateObject is adding @MainActor compliance to my View under the hood because it's wrappedValue and projectedValue properties are marked as @MainActor, while on @State they are not. @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) @frozen @propertyWrapper public struct StateObject&lt;ObjectType&gt; : DynamicProperty where ObjectType : ObservableObject { ... @MainActor public var wrappedValue: ObjectType { get } .... @MainActor public var projectedValue: ObservedObject&lt;ObjectType&gt;.Wrapper { get } } One solution for this is to mark my View explicitly as @MainActor struct ViewModel: View but it have it side effects, for example code like: Button(action: resendButtonAction) { Text(resendButtonAttributedTitle()) } Will result a warning Converting function value of type '@MainActor () -&gt; ()' to '() -&gt; Void' loses global actor 'MainActor' While could be easily solved by using instead Button(action: { resendButtonAction() } ) { Text(resendButtonAttributedTitle()) } I still feel like marking the whole View explicitly as @MainActor is not a good practice. Adding fake @StateObject property to my view also do the trick, but it's a hack (the same for @FetchRequest). Can anyone think of a more robust solution for this?
1
1
1.1k
May ’24
How to make sysctl and gettimeofday thread-safe in Swift?
I am trying to sync the ntp time from the server using Kronos library. However, I believe the code is not fully protected from multithreading access since it is using low level system code. So, does anyone know how can I ensure sysctl and gettimeofday are thread-safe when calling them? Or, is there any thread-safe alternative to get the same result? func currentTime() -&gt; TimeInterval { var current = timeval() let systemTimeError = gettimeofday(&amp;current, nil) != 0 assert(!systemTimeError, "system clock error: system time unavailable") return Double(current.tv_sec) + Double(current.tv_usec) / 1_000_000 } static func systemUptime() -&gt; TimeInterval { var mib = [CTL_KERN, KERN_BOOTTIME] var size = MemoryLayout&lt;timeval&gt;.stride var bootTime = timeval() let bootTimeError = sysctl(&amp;mib, u_int(mib.count), &amp;bootTime, &amp;size, nil, 0) != 0 assert(!bootTimeError, "system clock error: kernel boot time unavailable") let now = currentTime() let uptime = Double(bootTime.tv_sec) + Double(bootTime.tv_usec) / 1_000_000 assert(now &gt;= uptime, "inconsistent clock state: system time precedes boot time") return now - uptime } I have thought of using NSLock but I can only protect from the getter (caller) not the setter (system)
14
0
511
May ’24
WKScriptMessageHandlerWithReply and strict concurrency checking
Hi, I'm trying to implement a type conforming to WKScriptMessageHandlerWithReply while having Swift's strict concurrency checking enabled. It's not been fun. The protocol contains the following method (there's also one with a callback, but we're in 2024): func userContentController( controller: WKUserContentController, didReceive message: WKScriptMessage ) async -> (Any?, String?) WKScriptMessage's properties like body must be accessed on the main thread. But since WKScriptMessageHandlerWithReply is not @MainActor, neither can this method be so marked (same for the conforming type). At the same time WKScriptMessage is not Sendable, so I can't handle it in Task { @MainActor in this method, because that leads to Capture of 'message' with non-sendable type 'WKScriptMessage' in a `@Sendable` closure That leaves me with @preconcurrency import - is that the way to go? Should I file a feedback for this or is it somehow working as intended?
3
0
252
May ’24