Reputation: 3110
I'm looking to multithread some code in Swift, but I'm wondering about how GCD handles threading. Does each new thread I create automatically run on a separate core (if available), or does it use another mechanism for assigning threads to cores?
Essentially what I want is to prevent the new threads I create from running concurrently on the same core; I want to guarantee they are on different cores (again, in the case they available).
I'm not writing an app for the App Store or anything, I just need it to run these threads on different cores on my multicore machine. From what I could find online, GCD decides for itself whether to run threads on different cores, but I could not gather whether this was simply based on availability or something else entirely. Thanks.
Upvotes: 0
Views: 311
Reputation: 66244
If you use either the Grand-Central Dispatch API (dispatch_async
, etc.) or higher-level APIs that use GCD (like NSOperationQueue
), GCD will pick the best thread for you, and therefore the best core for you, depending on a variety of factors. You only have control over the GCD queue, not the thread or the processor core.
You can also create your own threads using NSThread
, but this generally isn't recommended unless you need to run your code on pre-GCD operating systems. I think the only way to guarantee two different cores are used is to have some code running on mainThread
and another on a detached thread. As far as I know, the even-more-granular control you're requesting isn't available via public APIs. (I'm reasonably sure it's possible using private APIs, but I don't know how.)
Upvotes: 2