title: OpenMP threads executing on the same cpu core
body: <p>I'm currently parallelizing program using openmp on a 4-core phenom2. However I noticed that my parallelization does not do anything for the performance. Naturally I assumed I missed something (falsesharing, serialization through locks, ...), however I was unable to find anything like that. Furthermore from the CPU Utilization it seemed like the program was executed on only one core. From what I found <code>sched_getcpu()</code> should give me the Id of the core the thread executing the call is currently scheduled on. So I wrote the following test program:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;sstream&gt;
  #include &lt;omp.h&gt;
  #include &lt;utmpx.h&gt;
  #include &lt;random&gt;
  int main(){
      #pragma omp parallel
      {
          std::default_random_engine rand;
          int num = 0;
      #pragma omp for
          for(size_t i = 0; i &lt; 1000000000; ++i) num += rand();
      auto cpu = sched_getcpu();
      std::ostringstream os;
          os&lt;&lt;"\nThread "&lt;&lt;omp_get_thread_num()&lt;&lt;" on cpu "&lt;&lt;sched_getcpu()&lt;&lt;std::endl;
          std::cout&lt;&lt;os.str()&lt;&lt;std::flush;
      std::cout&lt;&lt;num;
      }
  }
  </code></pre>
  
  <p>On my machine this gives the following output(the random numbers will vary of course):</p>
  
  <pre><code>Thread 2 on cpu 0 num 127392776
  Thread 0 on cpu 0 num 1980891664
  Thread 3 on cpu 0 num 431821313
  Thread 1 on cpu 0 num -1976497224
  </code></pre>
  
  <p>From this I assume that all threads execute on the same core (the one with id 0). To be more certain I also tried the approach from <a href="https://stackoverflow.com/a/6030091/201270">this answer</a>. The results where the same. Additionally using <code>#pragma omp parallel num_threads(1)</code> didn't make the execution slower (slightly faster in fact), lending credibility to the theory that all threads use the same cpu, however the fact that the cpu is always displayed as <code>0</code> makes me kind of suspicious. Additionally I checked <code>GOMP_CPU_AFFINITY</code> which was initially not set, so I tried setting it to <code>0 1 2 3</code>, which should bind each thread to a different core from what I understand. However that didn't make a difference. </p>
  
  <p>Since develop on a windows system, I use linux in virtualbox for my development. So I though that maybe the virtual system couldn't access all cores. However checking the settings of virtualbox showed that the virtual machine should get all 4 cores and executing my test program 4 times at the same time seems to use all 4 cores judging from the cpu utilization (and the fact that the system was getting very unresponsive). </p>
  
  <p>So for my question is basically what exactly is going on here. More to the point: 
  <strong>Is my deduction that all threads use the same core correctly? If it is, what could be the reasons for that behavious?</strong></p>