title: Why settting CPU affinity make threads run slower?
body: <p>all.</p>
  
  <p>I wrote a small case to test the multi-threaded producer/consumer model. My testbed is a low performance PC(8G RAM, J1900 CPU with 4 cores). I isolated the core 0 for Linux kernel, core 1-3 are unused. The producer thread runs on core 1, allocates 5000000 small objects, put them to a global queue. The consumer thread runs on core 2 and deallocate the objects from the queue. But I found if I do not set their CPU affinity(that is, they run on same core 0), the time performance get better than setting CPU affinity(8.76s VS 14.66s). The test results keep similar. Could someone explain the reason for me? IF my premise is incorrect("Setting CPU affinity can improve multi-threaded process' performance"), it should not get worse at least. My code slice listed below:</p>
  
  <pre><code>void producer() {
    Timestamp begin;
  
    for ( int i = 0; i&lt;data_nb; ++i ) {
      Test* test = new Test(i, i+1);
      queue.enqueue(test);
    }
  
    Timestamp end;
    TimeDuration td = end-begin;
    printf("producer: %ldms(%.6fs)\n", td.asMicroSecond(), td.asSecond());
  }
  
  void consumer() {
    Timestamp begin;
  
    do {
      Test* test = queue.dequeue();
      if ( test ) {
        nb.add(1); // nb is an atomic counter
        delete test;
        test = nullptr;
      }
    } while ( nb.get() &lt; data_nb );
  
    Timestamp end;
    TimeDuration td = end-begin;
    //printf("%d data consumed\n", nb.get());
    printf("consumer: %ldms(%.6fs)\n", td.asMicroSecond(), td.asSecond());
  }
  </code></pre>