title: CPU Affinity Masks (Putting Threads on different CPUs)
body: <p>I have 4 threads, and I am trying to set thread 1 to run on CPU 1, thread 2 on CPU 2, etc.
  However, when I run my code below, the affinity masks are returning the correct values, but when I do a sched_getcpu() on the threads, they all return that they are running on CPU 4.</p>
  
  <p>Anybody know what my problem here is?</p>
  
  <p>Thanks in advance!</p>
  
  <pre><code>#define _GNU_SOURCE
  #include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sched.h&gt;
  #include &lt;errno.h&gt;
  
  void *pthread_Message(char *message)
  {
      printf("%s is running on CPU %d\n", message, sched_getcpu());
  }
  
  int main()
  {
      pthread_t thread1, thread2, thread3, thread4;
      pthread_t threadArray[4];
      cpu_set_t cpu1, cpu2, cpu3, cpu4;
      char *thread1Msg = "Thread 1";
      char *thread2Msg = "Thread 2";
      char *thread3Msg = "Thread 3";
      char *thread4Msg = "Thread 4";
      int thread1Create, thread2Create, thread3Create, thread4Create, i, temp;
  
      CPU_ZERO(&amp;cpu1);
      CPU_SET(1, &amp;cpu1);
      temp = pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &amp;cpu1);
      printf("Set returned by pthread_getaffinity_np() contained:\n");
      for (i = 0; i &lt; CPU_SETSIZE; i++)
          if (CPU_ISSET(i, &amp;cpu1))
              printf("CPU1: CPU %d\n", i);
  
      CPU_ZERO(&amp;cpu2);
      CPU_SET(2, &amp;cpu2);
      temp = pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &amp;cpu2);
      for (i = 0; i &lt; CPU_SETSIZE; i++)
          if (CPU_ISSET(i, &amp;cpu2))
              printf("CPU2: CPU %d\n", i);
  
      CPU_ZERO(&amp;cpu3);
      CPU_SET(3, &amp;cpu3);
      temp = pthread_setaffinity_np(thread3, sizeof(cpu_set_t), &amp;cpu3);
      for (i = 0; i &lt; CPU_SETSIZE; i++)
          if (CPU_ISSET(i, &amp;cpu3))
              printf("CPU3: CPU %d\n", i);
  
      CPU_ZERO(&amp;cpu4);
      CPU_SET(4, &amp;cpu4);
      temp = pthread_setaffinity_np(thread4, sizeof(cpu_set_t), &amp;cpu4);
      for (i = 0; i &lt; CPU_SETSIZE; i++)
          if (CPU_ISSET(i, &amp;cpu4))
              printf("CPU4: CPU %d\n", i);
  
      thread1Create = pthread_create(&amp;thread1, NULL, (void *)pthread_Message, thread1Msg);
      thread2Create = pthread_create(&amp;thread2, NULL, (void *)pthread_Message, thread2Msg);
      thread3Create = pthread_create(&amp;thread3, NULL, (void *)pthread_Message, thread3Msg);
      thread4Create = pthread_create(&amp;thread4, NULL, (void *)pthread_Message, thread4Msg);
  
      pthread_join(thread1, NULL);
      pthread_join(thread2, NULL);
      pthread_join(thread3, NULL);
      pthread_join(thread4, NULL);
  
      return 0;
  }
  </code></pre>