Dispatch

RSS for tag

Execute code concurrently on multicore hardware by submitting work to dispatch queues managed by the system using Dispatch.

Dispatch Documentation

Pinned Posts

Posts under Dispatch tag

31 Posts
Sort by:
Post marked as solved
4 Replies
860 Views
I'm running a simulation (SwiftUI app), which has 100 steps. I need each step to be executed in order. A first try was to dispatch with delay to schedule each second: for step in 0..<100 { DispatchQueue.main.asyncAfter(deadline: .now() + Double(step) * 1.0) { // simulation code } } Very poor results as 100 running threads are too much load for the system. So I split in 2 stages: for bigStep in 0..<10 { DispatchQueue.main.asyncAfter(deadline: .now() + Double(bigStep) * 10.0 ) { for step in 0..<10 { DispatchQueue.main.asyncAfter(deadline: .now() + Double(step) * 1.0) { // simulation code } } } } It works much better, as now there are a max of 20 threads active (in fact I create more levels to limit to a max of 8 concurrent threads). It addition, it allows to interrupt the simulation before end. My questions: is it the appropriate pattern ? Would a timer be better ? Other options ?
Posted
by
Post marked as solved
3 Replies
1.4k Views
Since updating to iOS 16.4.1, our app crashes randomly with the following error message. Exception Codes: 0x0000000000000001, 0x0000000199d542c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [499] Triggered by Thread: 2 Thread 2 Crashed: 0 libdispatch.dylib 0x199d542c0 _dispatch_assert_queue_fail + 120 1 libdispatch.dylib 0x199d54248 dispatch_assert_queue + 196 2 UIKitCore 0x1949c870c -[UIImageView _mainQ_beginLoadingIfApplicable] + 88 3 UIKitCore 0x19495db34 -[UIImageView setHidden:] + 68 4 UIKitCore 0x19492f128 -[UIButtonLegacyVisualProvider _updateImageView] + 372 5 UIKitCore 0x19492ed78 -[UIButtonLegacyVisualProvider layoutSubviews] + 116 6 UIKitCore 0x19492ecc4 -[UIButton layoutSubviews] + 40 7 UIKitCore 0x1948fbef4 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1920 8 QuartzCore 0x193db64ac CA::Layer::layout_if_needed(CA::Transaction*) + 500 9 QuartzCore 0x193dc9a28 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 148 10 QuartzCore 0x193ddae54 CA::Context::commit_transaction(CA::Transaction*, double, double*) + 444 11 QuartzCore 0x193e0a3c0 CA::Transaction::commit() + 648 12 QuartzCore 0x193e54b08 CA::Transaction::release_thread(void*) + 228 13 libsystem_pthread.dylib 0x1f2214b9c _pthread_tsd_cleanup + 620 14 libsystem_pthread.dylib 0x1f2217560 _pthread_exit + 84 15 libsystem_pthread.dylib 0x1f22140cc _pthread_wqthread_exit + 80 16 libsystem_pthread.dylib 0x1f2213e64 _pthread_wqthread + 424 17 libsystem_pthread.dylib 0x1f2213b7c start_wqthread + 8 I have trouble interpreting where our error lies within the exception. Can anyone give me a hint as to what kind of problem this might be? Kind regards
Posted
by
Post not yet marked as solved
3 Replies
767 Views
has anyone else noticed much slower GCD runs in newer MacOS / Catalyst this seems like it used to be blazing fast: dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{ // code to run }); now if I run a block on this type of queue versus the main thread, the dispatched code runs much slower vs main thread. not 10%, like multiple slower. i am not sure yet if it is the code run time or time for dispatch to trigger. trying to focus in on what is the problem on our side and get some metrics, but if anyone has seen this issue, it might be useful to compare notes.
Posted
by
Post not yet marked as solved
1 Replies
700 Views
I'm using JSONDecoder().decode(T.Type, from: data) to decode a JSON response from a server. It works in some cases but eventually my program crashes with the error "Stack buffer overflow". The size of the JSON data I'm trying to decide is about 16k, which is large, but not unusually so. The decode is happening in a non-main thread, but I tried pushing it into the main thread with the same results. Most of these crashes occur in the simulator rather than on a real device, but I'd like to figure out the problem anyway. I thought I'd try dispatching the work into a queue with a larger stack size, but I couldn't figure out how to make one. Is it possible? Thanks, Frank
Posted
by
Post not yet marked as solved
0 Replies
696 Views
I understand UI updates have to be on the main thread, but what about SKSpriteNode's texture? Can I update that in the background? I can update it in the background and it works like I want it to. No crashes, warnings, etc. I did verify that the thread is not the main thread via [NSThread isMainThread]. I have since wrapped the texture change in a dispatch_sync on the main queue and it works the same as without it. Regards, Patrick
Posted
by
Post not yet marked as solved
1 Replies
843 Views
Experiencing an increased amount of crash reports with the latest release of the app. I've spent some time online understanding the meaning of Unbalanced call to dispatch_group_leave() however, I am struggling to pinpoint what's the source of the problem inside the codebase. I wish you can help me with these crash logs. Will calling a closure from inside CoreData context's perform() will eventually result into this crash and cause leave() to get called multiple times? The main code was there for long time, the only recent change was to wrap some code around CoreData context perform() or performAndWait() to avoid concurrency issues. 2023-05-20_10-42-03.5467_+0100-e8b3d9b142b8fd3d11c72abc01ad2fbcfbe92aee.crash 2023-05-22_20-57-32.2620_+0400-5d4c76afe1e42937cf09035d3034fb33ec40f0c9.crash 2023-05-21_19-36-18.3480_+0100-c01f62a2b78cae616c6202940f06220b7ea3b760.crash 2023-05-16_15-29-43.3962_+0100-ebb44a6156a3771271acfdd459546fe1271eb370.crash
Posted
by
Post marked as solved
1 Replies
1.2k Views
Do run loops use an operation queue under the hood? When I dispatch to the mian queue, I know it will run on the mian thread, which means it will be handled b the main thread's run loop. But is the other way around correct? More specific question, is it possible somehow that the following code will return true? OperationQueue.current != OperationQueue.main && Thread.isMainThread I tried to do for example to dispatch to the main thread using a timer. myQueue.sync { let timer = Timer(timeInterval: 1, repeats: false) { _ in let curr = OperationQueue.current let main = OperationQueue.main print("\(String(describing: curr)) \(main)") } RunLoop.main.add(timer, forMode: .common) } And got the same pointer. But maybe some other way of dispatching to the main run loop will give different results, possibly that is why OperationQueue.current can return nil.
Posted
by
Post not yet marked as solved
0 Replies
1.3k Views
In What's New In Swift, a new DispatchSerialQueue-backed actor was introduced. We're able to call MainActor-annotated functions using DispatchQueue.main.async without errors or warnings. For example: @MainActor func randomFunc() { print("Hello World") } DispatchQueue.main.async { randomFunc() } However calling a globalActor-annotated function or a regular actor-isolated function backed by a DispatchSerialQueue, we get the warning Actor-isolated instance method 'randomFunc()' can not be referenced from a non-isolated context; this is an error in Swift 6. Code here: actor MyActor { private let queue: DispatchSerialQueue nonisolated var unownedExecutor: UnownedSerialExecutor { queue.asUnownedSerialExecutor() } init(queue: DispatchSerialQueue) { self.queue = queue } func randomFunc() { print("Hello World!") } } let queue = DispatchSerialQueue(label: "actorQueue") let actor = MyActor(queue: queue) queue.async { actor.randomFunc() // Warning here } Although it has a warning, the code still runs successfully and prints Hello World, but it would also do so from another DispatchQueue not used by the actor (this was tested in Version 15.0 beta (15A5160n) Playground). My question: Can we remove the warning resulting from calling an actor isolated function backed by DispatchSerialQueue A using A.async { }, if that's safe behavior? If it's not safe, why not?
Posted
by
Post marked as solved
2 Replies
604 Views
Below is some simple code that does nothing, saves nothing. Yet the memory usage keeps rising. Am I missing something or is this a bug? The code requires 6 core CPU minimum. ContentView.swift import SwiftUI import Combine struct ContentView: View { @EnvironmentObject var loopClass:LoopClass var body: some View { ProgressView(value: Float(loopClass.loop_count), total: Float(loopClass.max_loops) ).progressViewStyle(.circular).padding() Button("Run looper", action: { loopClass.loopFunc() } ) } } LoopClass.swift import Combine class LoopClass: ObservableObject { @Published var loop_count = 0 @Published var max_loops = 0 func loopFunc () { let loopSet = [ 1, 3, 5, 7, 11, 13 ] max_loops = Int(pow(Double(loopSet.count), 13.0)) print("max_loops = \(max_loops)") for loop13 in loopSet { DispatchQueue.global().async { for loop12 in loopSet { for loop11 in loopSet { for loop10 in loopSet { for loop9 in loopSet { for loop8 in loopSet { for loop17 in loopSet { for loop16 in loopSet { for loop5 in loopSet { for loop4 in loopSet { for loop3 in loopSet { for loop2 in loopSet { for loop1 in loopSet { DispatchQueue.main.async{ self.loop_count += 1 } } }}}}}}}}}}} } // DQ } // for loop13 } }
Posted
by
Post marked as solved
8 Replies
3.0k Views
I see this warning when my app runs: Thread running at QOS_CLASS_USER_INTERACTIVE waiting on a lower QoS thread running at QOS_CLASS_DEFAULT. Investigate ways to avoid priority inversions This is true; I know what is going on. I'd like this other thread to have a higher priority. But how do I set the "QOS class" for a thread? Searching developer.apple.com for QOS_CLASS_USER_INTERACTIVE doesn't find much. It seems that dispatch queues have priorities, but in this case I have a thread, not a dispatch queue. Any ideas?
Posted
by
Post not yet marked as solved
4 Replies
1k Views
I had 2 crash report from our customer. Both crash point is same but there is no my code on crash stack trace. How to fix this kind of crash problem. Thread 1 Crashed:: Dispatch queue: com.apple.root.background-qos 0 libsystem_kernel.dylib 0x7ff81b84922a __pthread_kill + 10 1 libsystem_pthread.dylib 0x7ff81b880f7b pthread_kill + 263 2 libsystem_c.dylib 0x7ff81b7caca5 abort + 123 3 libc++abi.dylib 0x7ff81b83b082 abort_message + 241 4 libc++abi.dylib 0x7ff81b82c23d demangling_terminate_handler() + 266 5 libobjc.A.dylib 0x7ff81b529023 _objc_terminate() + 96 6 libc++abi.dylib 0x7ff81b83a4a5 std::__terminate(void (*)()) + 8 7 libc++abi.dylib 0x7ff81b83a456 std::terminate() + 54 8 libdispatch.dylib 0x7ff81b701a58 _dispatch_client_callout + 28 9 libdispatch.dylib 0x7ff81b704500 _dispatch_continuation_pop + 463 10 libdispatch.dylib 0x7ff81b715dff _dispatch_source_invoke + 2184 11 libdispatch.dylib 0x7ff81b7116a2 _dispatch_root_queue_drain + 343 12 libdispatch.dylib 0x7ff81b711e4d _dispatch_worker_thread2 + 160 13 libsystem_pthread.dylib 0x7ff81b87dc9d _pthread_wqthread + 256 14 libsystem_pthread.dylib 0x7ff81b87cc67 start_wqthread + 15 This crash point is exactly same with this post. I do not throw C++ exception. https://developer.apple.com/forums/thread/725197
Posted
by
Post not yet marked as solved
5 Replies
644 Views
In a thread titled “Avoid Dispatch Global Concurrent Queues” [1], Quinn links to a video from WWDC 2015 Session 718, “Building Responsive and Efficient Apps with GCD”. However, this video is not available from the Apple Developer Videos site; only a half dozen or so videos from 2015 are available. This same issue of the missing video came up about five years ago, when Quinn stated that the video had been mistakenly removed but had been restored. Now it’s gone again. :sad_face: Could this video be restored again, or at least its transcript? While I understand that Apple is focused on Swift concurrency, I need to maintain some Objective-C code that uses GCD, and in tracking down some performance issues, I would like to better understand the tradeoffs in the existing code and make improvements where I can. I don’t have the resources to reimplement the code in Swift right now. (More generally, why can't Apple just leave all these videos online indefinitely, for historical purposes at least? Couldn't the ones deemed “old and misleading” just be tagged with a banner like the legacy documentation has?) [1] I like to think of these valuable threads as “Quinn Technical Notes”; I have a page in my Notes app that holds links to the ones I’ve found.
Posted
by
Post not yet marked as solved
7 Replies
727 Views
Hi! I have a xcode workspace with first objectiveC framework (let’s call it framework#1). This framework has some singletons (+(instancetype)shared using the dispatch_once idiom. This code is pretty straight forward and used everywhere : + (instancetype)shared { static dispatch_once_t onceToken; static OGAKeyManager *instance = nil; dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); return instance; } I have a second framework (framework#2) in Swift that uses theses singletons (the framework#1 is added as do not embeed in the framework settings). And I have an application that uses both frameworks. If I make a breakpoint inside the dispatch_once alloc/init, I see that I enter 2 times : once when the shared method is called from framework#1 and another one when it’s called from framework#2. How is that even possible ? Isn't dispatch_once supposed to handle this ? I asked chatGPT, it points out to some objC/Swift interoperability, but honestly, I don't see what I can do to make it work correctly. There is no circular dependency (framwork#2 uses framwork#1, but framwork#1 has no clue of framwork#2 existence) Maybe it has something to do with sandbox, but I don't see how can it be. Does anyone experienced some weird behavior like this ? Thanks
Posted
by
Post marked as solved
6 Replies
1.1k Views
A handful of my customers have reported a consistent freeze in my app (smells like either a thread deadlock or an infinite recursion to me). It's working properly for most people, but if 3 people are reporting it to me that says to me that probably 300 are experiencing it but staying quiet. It happens every time they take a certain kind of action. But it never happens to me so I can't figure out what is breaking. No crash is happening, so I'm not getting any reports via Firebase. It doesn't appear to be related to their data, because they can have someone else use a different device, login to their account, download all of their data, and then successfully do the thing that freezes 100% of the time on their original device. I've got one of these customers set up on TestFlight so I can send them test versions of the app with some debug collection code. I created my own version of a tracelog and write a line to a file whenever I start/end a function. I've added those tracelog calls to a bunch of methods and classes (but not all). The action that causes the freeze is when they tap Edit on a record. What's supposed to happen is that I modally present a nav controller containing an EditBlahViewController. The trace logs show that the EditBlahViewController gets through viewDidLoad, viewWillAppear, two rounds of viewWillLayoutSubviews/viewDidLayoutSubviews... but then never gets to viewDidAppear. I've tried updating more and more functions/classes with the tracelog calls, but I can't find any infinite recursions. I've added tracelogs to all calls involving dispatching to other threads (especially synchronous dispatches to the main thread) but I don't see any deadlocks. Every dispatch to main starts and ends properly and then goes on to the next thing. User is on iOS 16.6.1 with an iPhone 12. I don't know what else to try. How can I debug this at a distance and figure out where the problem is?
Posted
by
Post not yet marked as solved
5 Replies
551 Views
class CalculatorViewModel : NSObject, ObservableObject, Identifiable { var id = UUID() @Published var output = "Disconnected" @Published var connected = false @Published var databasePath = String() enum itemType : Int{ case angle = 1 case degree = 2 case grip1 = 3 case grip2 = 4 } struct test_Array: Identifiable { var id = UUID() var time: String var swingNum : Int var dataSeqInSwing: Int var timeStampInSeq: Double var itemType: Int var value: Double } @Published var testDBdata = [test_Array] () ..... private var centralManager: CBCentralManager? func connectCalculator() { output = "Connecting..." centralQueue = DispatchQueue(label: "test.discovery") centralManager = CBCentralManager(delegate: self, queue: centralQueue) } .... func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { ..... if characteristic.uuid == outputCharUUID, var data = characteristic.value { ..... DispatchQueue.main.async() { for index in tupleSets { strItemSets = index.components(separatedBy: ",") ....... var itemN = 1 for indexStr in strItemSets { self.golfDBdata[numDB].dataSeqInSwing = countItem. <= Error self.golfDBdata[numDB].itemType = itemN self.golfDBdata[numDB].value = Double(strItemSets[itemN]) ?? 0.0
Posted
by
Post marked as solved
2 Replies
430 Views
I have folder monitoring code using makeFileSystemObjectSource. The events are triggered for everything else, but not for when I edit a file with nano terminal command. Am I doing something wrong? Is it a bug? Is this intended and unfixable? Code sample: monitoredFolderFileDescriptor = open(currentlyMonitoredPath, O_EVTONLY) folderMonitorSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: monitoredFolderFileDescriptor, eventMask: .all, queue: .main) folderMonitorSource?.setEventHandler { // ... } folderMonitorSource?.setCancelHandler { // ... } folderMonitorSource?.resume()
Posted
by
Post not yet marked as solved
0 Replies
464 Views
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.
Posted
by
Post not yet marked as solved
2 Replies
1.2k Views
The Apple App Store is saying my react native mobile app crashes on launch. I don't experience the same in my dev environment, neither in VScode nor in Xcode. When I run the app in Xcode, it compiles and works as expected but I found a message in the console output that indicates a possible thread inversion. In the provided backtrace, it seems to be related to a WebSocket connection in my React Native app. My app starts at a login page. Once the user enters their credentials they click login and a call is made to the app server which is hosted on Heroku. I think I should review the code related to the mentioned thread (TID: 1269068) and identify where the -[UIApplication applicationState] is being called. ChatGPT is suggesting to make sure that this call, and any other UI-related calls, are wrapped within a dispatch to the main thread. My knowledge of reading the backtrace is limited and i'm unsure how to map the backtrace to my actual javascript code. I've added the backtrace below: Thread Performance Checker: Thread running at User-interactive quality-of-service class waiting on a lower QoS thread running at Default quality-of-service class. Investigate ways to avoid priority inversions PID: 78136, TID: 1269068 Backtrace ================================================================= 3 xp1 0x0000000100ae679c -[SRRunLoopThread runLoop] + 44 4 xp1 0x0000000100ae0cc4 +[NSRunLoop(SRWebSocket) SR_networkRunLoop] + 56 5 xp1 0x0000000100ae50cc -[SRProxyConnect _openConnection] + 72 6 xp1 0x0000000100ae4584 -[SRProxyConnect _configureProxy] + 916 7 xp1 0x0000000100ae3d78 -[SRProxyConnect openNetworkStreamWithCompletion:] + 92 8 xp1 0x0000000100ae8530 -[SRWebSocket open] + 624 9 xp1 0x0000000100754804 -[RCTReconnectingWebSocket start] + 148 10 xp1 0x0000000100742b08 -[RCTPackagerConnection init] + 416 11 xp1 0x0000000100742948 __49+[RCTPackagerConnection sharedPackagerConnection]_block_invoke + 36 12 libdispatch.dylib 0x000000010389993c _dispatch_client_callout + 16 13 libdispatch.dylib 0x000000010389b3dc _dispatch_once_callout + 84 14 xp1 0x00000001007428fc +[RCTPackagerConnection sharedPackagerConnection] + 88 15 xp1 0x00000001007d1afc -[RCTDevSettings initialize] + 164 16 xp1 0x000000010072df4c -[RCTModuleData _initializeModule] + 96 17 xp1 0x000000010072d89c -[RCTModuleData setUpInstanceAndBridge:] + 2168 18 xp1 0x000000010072f3b4 -[RCTModuleData instance] + 1168 19 xp1 0x00000001006d7074 -[RCTCxxBridge moduleForName:lazilyLoadIfNecessary:] + 712 20 xp1 0x00000001007382d4 -[RCTModuleRegistry moduleForName:lazilyLoadIfNecessary:] + 140 21 xp1 0x000000010073823c -[RCTModuleRegistry moduleForName:] + 48 22 xp1 0x00000001007e2ba8 -[RCTPerfMonitor devMenuItem] + 92 23 xp1 0x00000001007e2a74 -[RCTPerfMonitor initialize] + 88 24 xp1 0x000000010072df4c -[RCTModuleData _initializeModule] + 96 25 xp1 0x000000010072d89c -[RCTModuleData setUpInstanceAndBridge:] + 2168 26 xp1 0x000000010072f5ec __25-[RCTModuleData instance]_block_invoke + 44 27 xp1 0x0000000100793d20 RCTUnsafeExecuteOnMainQueueSync + 52 28 xp1 0x000000010072f254 -[RCTModuleData instance] + 816 29 xp1 0x00000001006db97c __49-[RCTCxxBridge _prepareModulesWithDispatchGroup:]_block_invoke + 156 30 libdispatch.dylib 0x00000001038980f0 _dispatch_call_block_and_release + 24 31 libdispatch.dylib 0x000000010389993c _dispatch_client_callout + 16 32 libdispatch.dylib 0x00000001038a96ac _dispatch_main_queue_drain + 1428 33 libdispatch.dylib 0x00000001038a9108 _dispatch_main_queue_callback_4CF + 40 34 CoreFoundation 0x00000001803ee1b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12 35 CoreFoundation 0x00000001803e88cc __CFRunLoopRun + 1936 36 CoreFoundation 0x00000001803e7d28 CFRunLoopRunSpecific + 572 37 GraphicsServices 0x000000018e7cdbc0 GSEventRunModal + 160 38 UIKitCore 0x00000001852bafdc -[UIApplication _run] + 868 39 UIKitCore 0x00000001852bec54 UIApplicationMain + 124 40 xp1 0x00000001004172e0 main + 96
Posted
by
Post not yet marked as solved
5 Replies
524 Views
When calling DispatchQueue.main.async or DispatchQueue.main.sync with a call to self without capturing self, I get a compiler error: Call to method 'asd' in closure requires explicit use of 'self' to make capture semantics explicit Since I usually use DispatchQueue.main.async, I'm now used to solving this error by capturing self like this: DispatchQueue.main.async { [self] in asd() } But this unfortunately doesn't seem to work with DispatchQueue.main.sync: DispatchQueue.main.async { [self] in asd() } This gives the compiler warning: Call to method 'asd' in closure requires explicit use of 'self' to make capture semantics explicit; this is an error in Swift 6 This warning only appears for DispatchQueue.main.sync and not for DispatchQueue.main.async. Why? How can I avoid having to prefix every method call with self. in this case?
Posted
by