Skip to content

Instantly share code, notes, and snippets.

@Coneko
Created December 7, 2012 17:24
Show Gist options
  • Save Coneko/4234842 to your computer and use it in GitHub Desktop.
Save Coneko/4234842 to your computer and use it in GitHub Desktop.
How to get your code to run on different cores in OSX / iOS without CHUD.
#import <pthread.h>
#import <mach/thread_act.h>
// These two functions are declared in mach/thread_policy.h, but are commented out.
// They are documented here: https://developer.apple.com/library/mac/#releasenotes/Performance/RN-AffinityAPI/_index.html
kern_return_t thread_policy_set(
thread_t thread,
thread_policy_flavor_t flavor,
thread_policy_t policy_info,
mach_msg_type_number_t count);
kern_return_t thread_policy_get(
thread_t thread,
thread_policy_flavor_t flavor,
thread_policy_t policy_info,
mach_msg_type_number_t *count,
boolean_t *get_default);
// Declare and/or define thread_routine_1 and thread_routine_2 here.
pthread_t thread1;
if(pthread_create_suspended_np(&thread1, NULL, thread_routine_1, NULL) != 0) abort();
mach_port_t mach_thread1 = pthread_mach_thread_np(thread1);
thread_affinity_policy_data_t policyData1 = { 1 };
thread_policy_set(mach_thread1, THREAD_AFFINITY_POLICY, (thread_policy_t)&policyData1, 1);
pthread_t thread2;
if(pthread_create_suspended_np(&thread2, NULL, thread_routine_2, NULL) != 0) abort();
mach_port_t mach_thread2 = pthread_mach_thread_np(thread1);
thread_affinity_policy_data_t policyData2 = { 2 };
thread_policy_set(mach_thread2, THREAD_AFFINITY_POLICY, (thread_policy_t)&policyData2, 1);
thread_resume(mach_thread1);
thread_resume(mach_thread2);
// This tells the system scheduler to try to run the two threads independently.
// It doesn't force the scheduling, so they might still get scheduled on the same core, but it helps.
@snkarnam
Copy link

snkarnam commented May 26, 2016

pretty cool. saved me a lot of time. on line 30 I believe there is a typo: thread1 should be thread2.

@lookfwd
Copy link

lookfwd commented Sep 10, 2016

Correct, there's a typo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment