Concurrency

RSS for tag

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

Pinned Posts

Posts under Concurrency tag

89 Posts
Sort by:
Post not yet marked as solved
1 Replies
255 Views
Hello, I recently implemented a lock that uses OSAllocatedUnfairLock on iOS 16+ and os_unfair_lock on below iOS 16. I know that using os_unfair_lock with Swift is tricky, and it is error-prone. For example, the famous open-source library Alamofire has even been using os_unfair_lock incorrectly in terms of Swift's lifecycle view. (They fixed it as in the link [1] ) So, I implemented a lock like below. To use os_unfair_lock safely, I used the Noncopyable protocol which was added in Swift 5.9 [2]. Also, I allocated memory on the heap to use os_unfair_lock. public struct UnfairLock: ~Copyable { public init() { if #available(iOS 16.0, *) { _osAllocatedUnfairLock = OSAllocatedUnfairLock() } else { self.unfairLock = UnsafeMutablePointer.allocate(capacity: 1) } } deinit { if #unavailable(iOS 16.0) { unfairLock!.deallocate() } } public func lock() { if #available(iOS 16.0, *) { osAllocatedUnfairLock.lock() } else { os_unfair_lock_lock(unfairLock!) } } public func unlock() { if #available(iOS 16.0, *) { osAllocatedUnfairLock.unlock() } else { os_unfair_lock_unlock(unfairLock!) } } public func with<T>(_ closure: () -> T) -> T { lock() defer { unlock() } return closure() } private var _osAllocatedUnfairLock: Any? private var unfairLock: UnsafeMutablePointer<os_unfair_lock_s>? @available(iOS 16.0, *) private var osAllocatedUnfairLock: OSAllocatedUnfairLock<Void> { // swiftlint:disable force_cast _osAllocatedUnfairLock as! OSAllocatedUnfairLock // swiftlint:enable force_cast } } However, I got several crashes on iOS 14-15 users like this (This app targets iOS 14+ and on iOS 16+, it uses OSAllocatedUnfairLock): (Sorry for using a third-party crash reporting tool's log, but I think it is enough to understand the issue) BUG IN CLIENT OF LIBPLATFORM: os_unfair_lock is corrupt Crashed: com.foo.bar.queue 0 libsystem_platform.dylib 0x6144 _os_unfair_lock_corruption_abort + 88 1 libsystem_platform.dylib 0xa20 _os_unfair_lock_lock_slow + 320 2 FoooBarr 0x159416c closure #1 in static FooBar.baz() + 6321360 3 FoooBarr 0x2e65b8 thunk for @escaping @callee_guaranteed @Sendable () -> () + 4298794424 (<compiler-generated>:4298794424) 4 libdispatch.dylib 0x1c04 _dispatch_call_block_and_release + 32 5 libdispatch.dylib 0x3950 _dispatch_client_callout + 20 6 libdispatch.dylib 0x6e04 _dispatch_continuation_pop + 504 7 libdispatch.dylib 0x6460 _dispatch_async_redirect_invoke + 596 8 libdispatch.dylib 0x14f48 _dispatch_root_queue_drain + 388 9 libdispatch.dylib 0x15768 _dispatch_worker_thread2 + 164 10 libsystem_pthread.dylib 0x1174 _pthread_wqthread + 228 11 libsystem_pthread.dylib 0xf50 start_wqthread + 8 ( libplatform's source code [3] suggests that __ulock_wait returns error, but I don't know the details) Per @eskimo 's suggestion in [4], I will change my code to use NSLock until OSAllocatedUnfairLock is available on all users' devices (i.e. iOS 16+), but I still want to know why this crash happens. I believe that making a struct Noncopyable is enough to use os_unfair_lock safely, but it seems that it is not enough. Did I miss something? Or is there any other way to use os_unfair_lock safely? [1] https://github.com/Alamofire/Alamofire/commit/1b89a57c2f272408b84d20132a2ed6628e95d3e2 [2] https://github.com/apple/swift-evolution/blob/1b0b339bc3072a83b5a6a529ae405a0f076c7d5d/proposals/0390-noncopyable-structs-and-enums.md [3] https://github.com/apple-open-source/macos/blob/ea4cd5a06831aca49e33df829d2976d6de5316ec/libplatform/src/os/lock.c#L555 [4] https://forums.developer.apple.com/forums/thread/712379
Posted
by
Post not yet marked as solved
1 Replies
446 Views
CIFormat static var such as RGBA16 give concurrency warnings: Reference to static property 'RGBA16' is not concurrency-safe because it involves shared mutable state; this is an error in Swift 6 Should all these formats be static let to suppress the warnings (future errors)?
Posted
by
Post not yet marked as solved
11 Replies
5.5k Views
I've just updated to Xcode 15.3 and iOS 17.4 (simulator). Every time I launch the app, I see a CPU spike keeping the CPU at 100% for about 30 seconds on a background thread. After those 30 seconds, there's a 'Thread Performance Checker' error posted on the console. This does not happen when using Xcode 15.2 and running on iOS 17.2. or iOS 16.4. Thread Performance Checker: Thread running at User-initiated quality-of-service class waiting on a thread without a QoS class specified (base priority 33). Investigate ways to avoid priority inversions PID: 70633, TID: 2132693 Backtrace ================================================================= 3 CFNetwork 0x000000018454094c estimatedPropertyListSize + 28648 4 CFNetwork 0x00000001843d7fc0 cfnTranslateCFError + 1864 5 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 6 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 7 CFNetwork 0x00000001843d7f8c cfnTranslateCFError + 1812 8 CFNetwork 0x0000000184540814 estimatedPropertyListSize + 28336 9 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 10 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 11 CFNetwork 0x0000000184540728 estimatedPropertyListSize + 28100 12 CFNetwork 0x0000000184540794 estimatedPropertyListSize + 28208 13 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 14 libdispatch.dylib 0x0000000105573210 _dispatch_once_callout + 84 15 CFNetwork 0x0000000184540780 estimatedPropertyListSize + 28188 16 CFNetwork 0x00000001844e8664 _CFNetworkHTTPConnectionCacheSetLimit + 191584 17 CFNetwork 0x00000001844e78dc _CFNetworkHTTPConnectionCacheSetLimit + 188120 18 CFNetwork 0x000000018439ce5c _CFURLCachePersistMemoryToDiskNow + 25460 19 CFNetwork 0x0000000184483068 _CFStreamErrorFromCFError + 609680 20 CFNetwork 0x000000018445105c _CFStreamErrorFromCFError + 404868 21 CFNetwork 0x000000018443a040 _CFStreamErrorFromCFError + 310632 22 CFNetwork 0x000000018453be14 estimatedPropertyListSize + 9392 23 CFNetwork 0x000000018440fa5c _CFStreamErrorFromCFError + 137092 26 CFNetwork 0x000000018445b398 _CFStreamErrorFromCFError + 446656 27 CFNetwork 0x0000000184459db8 _CFStreamErrorFromCFError + 441056 28 CFNetwork 0x000000018445cf60 _CFStreamErrorFromCFError + 453768 29 CFNetwork 0x0000000184541838 estimatedPropertyListSize + 32468 30 libdispatch.dylib 0x000000010556fec4 _dispatch_call_block_and_release + 24 31 libdispatch.dylib 0x000000010557173c _dispatch_client_callout + 16 32 libdispatch.dylib 0x0000000105579a30 _dispatch_lane_serial_drain + 916 33 libdispatch.dylib 0x000000010557a774 _dispatch_lane_invoke + 420 34 libdispatch.dylib 0x000000010557b6e4 _dispatch_workloop_invoke + 864 35 libdispatch.dylib 0x00000001055871a8 _dispatch_root_queue_drain_deferred_wlh + 324 36 libdispatch.dylib 0x0000000105586604 _dispatch_workloop_worker_thread + 488 37 libsystem_pthread.dylib 0x0000000106b87924 _pthread_wqthread + 284 38 libsystem_pthread.dylib 0x0000000106b866e4 start_wqthread + 8
Posted
by
Post marked as solved
2 Replies
1.4k Views
The new Xcode 15.3 Release Candidate produces errors with strict concurrency checking that the usual pattern of using OSLog with a static property like static let logger = Logger(...) is not safe. "Static property 'logger' is not concurrency-safe because it is not either conforming to 'Sendable' or isolated to a global actor; this is an error in Swift 6" Is Logger thread safe and just not marked Sendable? Would it be "safe" to use nonisolated(unsafe) static let logger = Logger(...)?
Posted
by
Post not yet marked as solved
6 Replies
540 Views
Dear Sirs, I've written a SwiftUI application in XCode where I'm using multiple threads which are synchronized by using NSLock and NSRecursiveLock. This works in Debug mode and in Release mode as long as I don't use the Swift Compiler - Code Generation -&gt; Optimization Level -O for "Optimize for Speed". This is unfortunately the default setting but it results in multiple threads accessing the same piece of code which is encapsulated inside a NSLock. Is this an intended behaviour? Thanks and best regards, Johannes
Posted
by
Post marked as solved
3 Replies
535 Views
I was wondering if there is a way, while debugging, to observe the 'QoS boosting' behavior that is implemented in various places to provide priority inversion avoidance. The pthread_override_qos_class_start/end_np header comments specifically say that overrides aren't reflected in the qos_class_self() and pthread_get_qos_class_np() return values. As far as I can tell the 'CPU Report' UI in Xcode also does not reflect this information (perhaps for the reason the header comments call out). Is there a direct mechanism to observe this behavior? Presumably a heuristic empirical test could be done to compare throughput of a queue that should have its priority boosted and one that should not, but I would prefer a less opaque means of verification if possible. Thanks in advance!
Posted
by
Post not yet marked as solved
4 Replies
585 Views
I am perplexed as to how to use async await. In the following example, I don't use GCD or performSelector(inBackground:with:). The view controller is NSViewController, but it doesn't make any difference if it's NSViewController or UIViewController. import Cocoa class ViewController: NSViewController { func startWriteImages() { Task{ let bool = await startWriteImagesNext() if bool { print("I'm done!") } } } func startWriteImagesNext() async -&gt; Bool { // pictures is a path to a folder in the sandbox folder // appDelegate.defaultFileManager is a variable pointing to FileManager.default in AppDelegate let pictURL = URL(fileURLWithPath: pictures) if let filePaths = try? self.appDelegate.defaultFileManager.contentsOfDirectory(atPath: pictURL.path) { for file in filePaths { let fileURL = pictURL.appending(component: file) if self.appDelegate.defaultFileManager.fileExists(atPath: fileURL.path) { let newURL = self.folderURL.appending(component: file) do { try self.appDelegate.defaultFileManager.copyItem(at: fileURL, to: newURL) } catch { print("Ugghhh...") } } } return true } return false } func startWriteImagesNext2() async -&gt; Bool { let pictURL = URL(fileURLWithPath: pictures) if let filePaths = try? self.appDelegate.defaultFileManager.contentsOfDirectory(atPath: pictURL.path) { DispatchQueue.global().async() { for file in filePaths { let fileURL = pictURL.appending(component: file) if self.appDelegate.defaultFileManager.fileExists(atPath: fileURL.path) { let newURL = self.folderURL.appending(component: file) do { try self.appDelegate.defaultFileManager.copyItem(at: fileURL, to: newURL) } catch { print("Ugghhh...") } } } } return true } return false } } In the code above, I'm saving each file in the folder to user-selected folder (self.folderURL). And the application will execute the print guy only when work is done. Since it's heavy-duty work, I want to use CCD or performSelector(inBackground:with:). If I use the former (startWriteImagesNext2), the application will execute the print guy right at the beginning. I suppose I cannot use GCD with async. So how can I perform heavy-duty work? Muchos thankos.
Posted
by
Post marked as solved
1 Replies
751 Views
Hello community, I am in search of a tutorial that comprehensively explains the proper utilization of SwiftData for updating model data in a background thread. From my understanding, there is extensive coverage on creating a model and loading model data into a view, likely due to Apple's detailed presentation on this aspect of SwiftData during WWDC23. Nevertheless, I am encountering difficulties in finding a complete tutorial that addresses the correct usage of SwiftData for model updates in a background thread. While searching the web, I came across a few discussions on Stack Overflow and this forum that potentially provide an approach. However, they were either incomplete or proved ineffective in practical application. I would greatly appreciate any links to tutorials that thoroughly cover this topic.
Posted
by
Post not yet marked as solved
1 Replies
572 Views
I have observed that in my application, Even If I set the QoS value of all the thread created to USER_INTERACTIVE, the OS is producing a warning "Thread running at User-Interactive QoS class waiting on a lower QoS thread running at Default QoS class. Investigate ways to avoid priority inversions". I am aware that it is not right to set all threads as USER_INTERACTIVE QoS, but If we assume this case for once, then it means that the OS can dynamically change the QoS of the threads even if we are explicitly setting it. Is this the correct understanding? Also, the main thread has QoS value USER_INTERACTIVE, then is it the case that its child threads will inherit the QoS value from the parent thread, If we are not setting any QoS for a pthread?
Posted
by
Post marked as solved
2 Replies
399 Views
Suppose I have the following function: func doWork(_ someValue: Int, completionHandler: () -&gt; Void) { let q = DispatchQueue() q.async { // Long time of work completionHandler() } } How do I turn it into async function so that I can call it using await doWork()? Are there guidelines/principles/practices for this purpose?
Posted
by
Post marked as solved
3 Replies
886 Views
Hello! I'm developing a SDK and a customer is experiencing a very rare crash (happening for < 10 users) for which there are no clear repro steps. In the attached backtrace of the crash, there are two threads #13 and #17 which seem to be accessing the same part of the code (named MyMethod2 in the file). Thread #17 is the one crashing during deallocation of some protobuf objects. We designed MyMethod2 to be called by at most one thread at any point in time by using a serial DispatchQueue. My question is: can we tell for sure that the threads #13 and #17 shown in the file were executing that shared code simultaneously just by looking at the trace? If so, there'd be a concurrency bug in my code that I need to fix, but I haven't found anything suspicious. If on the other hand, these two threads were both used by the serial queue but at different times, then the problem is elsewhere. Thank you for your help! The two threads: Thread 13 name: Thread 13: 0 libsystem_kernel.dylib 0x00000001f61a0cb0 write (libsystem_kernel.dylib) 1 CoreFoundation 0x00000001aed14f68 fileWrite (CoreFoundation) 2 CoreFoundation 0x00000001aed14c40 CFWriteStreamWrite (CoreFoundation) 3 [MyHiddenAppName] 0x0000000107b81f8c NSOutputStream.write(_:) 4 [MyHiddenAppName] 0x0000000107ab6640 specialized MyMethod2 5 [MyHiddenAppName] 0x0000000107ab6cf0 partial apply for closure #1 in MyMethod1 6 [MyHiddenAppName] 0x0000000102ba0538 thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>:0) 7 libdispatch.dylib 0x00000001b6c4f6a8 _dispatch_call_block_and_release (libdispatch.dylib) [...] Thread 17 name: Thread 17 Crashed: 0 libswiftCore.dylib 0x00000001a8467d70 _swift_release_dealloc (libswiftCore.dylib) 1 libswiftCore.dylib 0x00000001a8469424 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) (libswiftCore.dylib) 2 [MyHiddenAppName] 0x0000000107a45b54 destroy for MyProtoStruct4 3 [MyHiddenAppName] 0x0000000107a55c64 outlined destroy of (MyProtoStruct2.OneOfEnum, MyProtoStruct2.OneOfEnum) 4 [MyHiddenAppName] 0x0000000107a4503c MyProtoStruct4._StorageClass.__deallocating_deinit 5 libswiftCore.dylib 0x00000001a8467d88 _swift_release_dealloc (libswiftCore.dylib) 6 libswiftCore.dylib 0x00000001a8469424 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) (libswiftCore.dylib) 7 [MyHiddenAppName] 0x0000000107a6a91c destroy for MyProtoStruct3 [...] 80 [MyHiddenAppName] 0x0000000107ab6108 specialized MyMethod2 81 [MyHiddenAppName] 0x0000000107ab6cf0 partial apply for closure #1 in MyMethod1 82 [MyHiddenAppName] 0x0000000102ba0538 thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>:0) 83 libdispatch.dylib 0x00000001b6c4f6a8 _dispatch_call_block_and_release (libdispatch.dylib) [...] crash_backtrace.txt
Posted
by
Post not yet marked as solved
3 Replies
490 Views
Hi! I'm seeing some confusing behavior with a propertyWrapper that tries to constrain its wrappedValue to MainActor. I'm using this in a SwiftUI.View… but I'm seeing some confusing behavior when I try to add that component to my graph. There seems to be some specific problem when body is defined in an extension. I start with a simple property wrapper: @propertyWrapper struct Wrapper<T> { @MainActor var wrappedValue: T } I then try a simple App with a View that uses a Wrapper: @main struct MainActorDemoApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @Wrapper var value = "Hello, world!" var body: some View { Text(self.value) } } This code compiles with no problems for me. For style… I might choose to define the body property of my MainActorDemoApp with an extension: @main struct MainActorDemoApp: App { // var body: some Scene { // WindowGroup { // ContentView() // } // } } extension MainActorDemoApp { var body: some Scene { WindowGroup { ContentView() // Call to main actor-isolated initializer 'init()' in a synchronous nonisolated context } } } struct ContentView: View { @Wrapper var value = "Hello, world!" var body: some View { Text(self.value) } } Explicitly marking my body as a MainActor fixes the compiler error: @main struct MainActorDemoApp: App { // var body: some Scene { // WindowGroup { // ContentView() // } // } } extension MainActorDemoApp { @MainActor var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @Wrapper var value = "Hello, world!" var body: some View { Text(self.value) } } So I guess the question is… why? Why would code that breaks when my body is in an extension not break when my body is in my original struct definition? Is this intended behavior? I'm on Xcode Version 15.2 (15C500b) and Swift 5.9.2 (swiftlang-5.9.2.2.56 clang-1500.1.0.2.5). It's unclear to me what is "wrong" about the code that broke… any ideas?
Posted
by
Post not yet marked as solved
1 Replies
868 Views
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?
Posted
by
Post not yet marked as solved
0 Replies
386 Views
Hi, Despite the following code works great on Windows and Linux (well, there is an OS layer stripped from the code), it hangs on macOS (pseudocode first): create non-blocking socketpair(AF_UNIX, SOCK_STREAM, ...); + a couple of fcntl(fd, ..., flags | O_NONBLOCK) spawn 128 pairs of threads (might be as little as 32, but will need several iterations to reproduce). Of course, there is the errno check to ensure there are no errors but EWOULDBLOCK / EAGAIN readers read a byte 10000 times: for (...) { while (read(fd[1]...) < 1) select(...); r++;} writers write a byte 10000 times: for (...) { while (write(fd[0]...) < 1) select(...); w++;} Join writers; Join readers; On Linux/Windows with the iterations number really cranked up, I'm getting a socket buffer overflow, so ::write returns EWOULDBLOCK, then I'm waiting on a socket until it's ready, continue, and after joining both sets of threads I see that bytes-read is equal to bytes-written, everything fine. However, on macOS I quickly end up in a strange lock when writers are waiting on ::select(...., &write_fds, ...) and readers on the corresponding ::select(..., &read_fds, ...); I have really no idea how that could happen except that the read/write is not thread-safe. However, it looks like POSIX docs and manpages state that it is (at least, reentrant). Could anyone point me in the right direction? Detailed code below: std::atomic<int> bytes_written(0); std::atomic<int> bytes_read(0); static constexpr int k_packets = 10000; static constexpr int k_threads = 32; std::vector<std::thread> writers; std::vector<std::thread> readers; writers.reserve(k_threads); readers.reserve(k_threads); for (int i = 0; i < k_threads; ++i) { writers.emplace_back([fd_write = fd[1], &bytes_written]() { char data = 'x'; for (int i = 0; i < k_packets; ++i) { while (::write(fd_write, &data, 1) < 1) { fd_set writefds; FD_ZERO(&writefds); FD_SET(fd_write, &writefds); assert(errno == EAGAIN || errno == EWOULDBLOCK); int retval = ::select(fd_write + 1, nullptr, &writefds, nullptr, nullptr); if (retval < 1) assert(errno == EAGAIN || errno == EWOULDBLOCK); } ++bytes_written; } }); readers.emplace_back([fd_read = fd[0], &bytes_read]() { char data; for (int i = 0; i < k_packets; ++i) { while (::read(fd_read, &data, 1) < 1) { fd_set readfds; FD_ZERO(&readfds); FD_SET(fd_read, &readfds); assert(errno == EAGAIN || errno == EWOULDBLOCK); int retval = ::select(fd_read + 1, &readfds, nullptr, nullptr, nullptr); if (retval < 1) assert(errno == EAGAIN || errno == EWOULDBLOCK); } ++bytes_read; } }); } for (auto& t : writers) t.join(); for (auto& t : readers) t.join(); assert(bytes_written == bytes_read);
Posted
by
Post marked as solved
1 Replies
446 Views
I am trying to use code from Apple's sample project on StoreKit (Implementing a store in your app using the StoreKit API). However, even if I don't make any changes to this sample project except enable "complete" concurrency checking in the build settings, I get warnings like Capture of 'self' with non-sendable type 'Store' in a '@Sendable' closure. How worried should I be about these warnings and how can I fix them?
Posted
by
Post not yet marked as solved
1 Replies
409 Views
I am following the iOS App Dev Tutorials on Adopting Swift concurrency and Persisting data. On Adopting Swift concurrency, it is mentioned that we can call an asynchronous function using the await keyword. Because the asynchronous function can suspend execution, we can use await only in asynchronous contexts, such as inside the body of another asynchronous function. Adopting Swift concurrency, it is also mentioned that we can create a new asynchronous context with a Task to call asynchronous functions from a synchronous context. Based on this information, I concluded that the main added value of a Task is to enable calling an asynchronous function in a synchronous context. On Persisting data, a Task object is created inside the declaration block of an asynchronous function: func load() async throws { let task = Task<[DailyScrum], Error> { let fileURL = try Self.fileURL() guard let data = try? Data(contentsOf: fileURL) else { return [] } let dailyScrums = try JSONDecoder().decode([DailyScrum].self, from: data) return dailyScrums } let scrums = try await task.value self.scrums = scrums } I didn't understand why it was necessary to create task. Based on what I learned from Adopting Swift concurrency, the context of load() is already asynchronous. Therefore, we can simply call asynchronous functions without the need to create a Task object. When I tried to run the code by removing the task, the app still worked the same, or at least that was my perception. I believe that there is another reason to use Task in this example other than just enabling calling asynchronous functions. However, this was not explicitly explained in the tutorials. Could you please explain why we use Task here? What is the added value and how it would improve the behavior of this app? Please keep in mind that I am a complete beginner and had no idea about what concurrency was two weeks ago. In case deleting task would not change anything, could you please confirm that my initial understanding was correct?
Posted
by
Post not yet marked as solved
1 Replies
455 Views
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libicucore.A.dylib 0x18c500918 icu::SimpleDateFormat::subFormat(icu::UnicodeString&amp;, char16_t, int, UDisplayContext, int, char16_t, icu::FieldPositionHandler&amp;, icu::Calendar&amp;, UErrorCode&amp;) const + 532 1 libicucore.A.dylib 0x18c500520 icu::SimpleDateFormat::format(icu::Calendar&amp;, icu::UnicodeString&amp;, icu::FieldPositionHandler&amp;, UErrorCode&amp;) const + 520 2 libicucore.A.dylib 0x18c5002f8 icu::SimpleDateFormat::format(icu::Calendar&amp;, icu::UnicodeString&amp;, icu::FieldPosition&amp;) const + 84 3 libicucore.A.dylib 0x18c42c4ac icu::DateFormat::format(double, icu::UnicodeString&amp;, icu::FieldPosition&amp;) const + 176 4 libicucore.A.dylib 0x18c535c40 udat_format + 352 5 CoreFoundation 0x189349a14 __cficu_udat_format + 68 6 CoreFoundation 0x189349898 CFDateFormatterCreateStringWithAbsoluteTime + 192 7 Foundation 0x18a432bf0 -[NSDateFormatter stringForObjectValue:] + 316 8 ShiningUtiliesKit 0x10522a130 SULog.log(:logDegree:file:method:line:) + 488 9 ShiningUtiliesKit 0x105229f3c SULog.debug(:file:method:line:) + 48 10 Calibration 0x1029f56bc closure #1 in Device.setDeviceData(:) + 487 (DeviceObject.swift:293) 11 Calibration 0x1029f3de0 specialized autoreleasepool(invoking:) + 23 (:0) [inlined] 12 Calibration 0x1029f3de0 Device.setDeviceData(_:) + 23 (DeviceObject.swift:291) [inlined] 13 Calibration 0x1029f3de0 closure #1 in closure #1 in variable initialization expression of Device.callback + 403 (DeviceObject.swift:221) 14 Calibration 0x1029f3548 thunk for @escaping @callee_guaranteed () -&gt; () + 27 (:0) 15 libdispatch.dylib 0x18907dcb8 _dispatch_call_block_and_release + 32 16 libdispatch.dylib 0x18907f910 _dispatch_client_callout + 20 17 libdispatch.dylib 0x18908dfa8 _dispatch_main_queue_drain + 984 18 libdispatch.dylib 0x18908dbc0 _dispatch_main_queue_callback_4CF + 44 19 CoreFoundation 0x18934b15c CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 16 20 CoreFoundation 0x189308a80 __CFRunLoopRun + 1996 21 CoreFoundation 0x189307c5c CFRunLoopRunSpecific + 608 22 HIToolbox 0x193884448 RunCurrentEventLoopInMode + 292 23 HIToolbox 0x193884284 ReceiveNextEventCommon + 648 24 HIToolbox 0x193883fdc _BlockUntilNextEventMatchingListInModeWithFilter + 76 25 AppKit 0x18cae2c54 _DPSNextEvent + 660 26 AppKit 0x18d2b8ebc -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716 27 AppKit 0x18cad6100 -[NSApplication run] + 476 28 AppKit 0x18caad3cc NSApplicationMain + 880 29 SwiftUI 0x1b3c14f80 0x1b3b3b000 + 892800 30 SwiftUI 0x1b44a530c 0x1b3b3b000 + 9872140 31 SwiftUI 0x1b48eb4f0 0x1b3b3b000 + 14353648 32 Calibration 0x1029fa1a0 static IntraoralScanMiniProgramApp.$main() + 51 (IntraoralScanMiniProgramApp.swift:14) [inlined] 33 Calibration 0x1029fa1a0 main + 63 (DeviceObject.swift:0) 34 dyld 0x188eb10e0 start + 2360 My mac APP has a crash about DateFormatter. mac version is 14.1.1. public class SULog { private let dateFormatter = { let dateFormatter = DateFormatter() dateFormatter.dateFormte = "yyy-MM-dd HH:mm:ss_sss" return dateFormatter } private var lock = NSLock() public func debug(_ message: Any...) { log(message) } public func log(_ message: Any...) { lock.lock() let date = Date() let dateString = dateFormatter.string(from:date) lock.unlock() print(dateString) } } var log:SULog! class AppDelegate: NSObject { func applicationWillFinishLaunching(_ notification: Notification) { log = SULog() } } public class Test { func test() { autoreleasepool { //.......other code log.debug("test") // crashed //........ other code } } } Any thought on this crash? Thanks
Posted
by
Post not yet marked as solved
8 Replies
746 Views
I'm having a hard time relying on TSAN to detect problems due to its rightful insistence on reporting data-races (I know, stick with me). Picture the following implementation of a lazily-allocated property in an Obj-C class: @interface MyClass { id _myLazyValue; // starts as nil as all other Obj-C ivars } @end @implementation MyClass - (id)myLazyValue { if (_myLazyValue == nil) { @synchronized(self) { if (_myLazyValue == nil) { _myLazyValue = &lt;expensive computation&gt; } } } return _myLazyValue; } @end The first line in the method is reading a pointer-sized chunk of memory outside of the protection provided by the @synchronized(...) statement. That same value may be written by a different thread within the execution of the @synchronized block. This is what TSAN complains about, but I need it not to. The code above ensures the ivar is written by at most one thread. The read is unguarded, but it is impossible for any thread to read a non-nil value back that is invalid, uninitialized or unretained. Why go through this trouble? Such a lazily-allocated property usually locks on @synchronized once, until (at most) one thread does any work. Other threads may be temporarily waiting on the same lock but again only while the value is being initialized. The cost of allocation and initialization is guaranteed to be paid once: multiple threads cannot initialize the value multiple times (that’s the reason for the second _myLazyValue == nil check within the scope of the @synchronized block). Subsequent accesses of the initialized property skip locking altogether, which is exactly the performance we want from a lazily-allocated, immutable property that still guarantees thread-safe access. Assuming there isn't a big embarrassing hole in my logic, is there a way to decorate specific portions of our sources (akin to #pragma statements that disable certain warnings) so that you can mark any read/write access to a specific value as "safe"? Is the most granular tool for this purpose the __attribute__((no_sanitize("thread")))? Ideally one would want to ask TSAN to ignore only specific read/writes, rather than the entire body of a function. Thank you!
Posted
by