1
#include "config.h"
2
#include <stdio.h>
3
#include <unistd.h>
4
#if HAVE_MACH_THREAD_POLICY_H
5
#include <mach/mach_init.h>
6
#include <mach/thread_policy.h>
7
// #include <mach/sched.h>
8
#endif
9
#if HAVE_DECL_SCHED_SETAFFINITY
10
//#define _GNU_SOURCE             /* See feature_test_macros(7) */
11
#include <sched.h>
12
#endif
13
#include <errno.h>
14
#include <caml/mlvalues.h>
15
16
CAMLprim value setcore(value which) {
17
  int numcores = sysconf( _SC_NPROCESSORS_ONLN );
18
  int w = Int_val(which) % numcores; // stay in the space of existing cores
19
#if HAVE_DECL_SCHED_SETAFFINITY
20
  cpu_set_t cpus;   
21
#endif
22
#if HAVE_MACH_THREAD_POLICY_H
23
  thread_affinity_policy_data_t affinityData;
24
#endif
25
  int retcode;
26
  int finished=0;
27
  while (finished==0)
28
    {
29
#if HAVE_DECL_SCHED_SETAFFINITY
30
      CPU_ZERO(&cpus); 
31
      CPU_SET (w,&cpus);
32
      //fprintf(stderr,"Trying to pin to cpu %d out of %d reported by the system\n",w,numcores);
33
      retcode = sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpus);
34
      if(retcode != 0) {
35
	fprintf(stderr,"Failed pinning to cpu %d, trying %d/2\n",w, w); 
36
	w=w/2;
37
      }
38
#endif
39
#if HAVE_MACH_THREAD_POLICY_H
40
      affinityData.affinity_tag = w;
41
      retcode = thread_policy_set(mach_thread_self(),
42
                        THREAD_AFFINITY_POLICY,
43
                        affinityData,
44
                        THREAD_AFFINITY_POLICY_COUNT);
45
      if(retcode) {
46
        fprintf(stderr,"MAC OS X: Failed pinning to cpu %d, trying %d/2\n",w, w);
47
        w=w/2;
48
      }
49
#endif
50
      else 
51
	{ //fprintf(stderr,"Succeeded pinning to cpu %d\n",w); 
52
	  finished=1;
53
	}
54
    }
55
  return Val_unit;
56
}