title: Why pthread slow down the code?
body: <p>I new to pthreads and I write this code for testing. I don't understand why if I run the code with only 1 pthread it complete faster than when I run with multiple pthreads.
  The code is the setting part of a genetic algoritm to resolve a TSP. 
  I have 3 linear arrays (city_x, city_y, city_id) that save the data: </p>
  
  <ul>
  <li>1 for the x</li>
  <li>1 for the y</li>
  <li>1 for the id of each city</li>
  </ul>
  
  <p>These array are like linearized and represent the elements of the population. Each element have NUM_CITIES data for x,y and id. So if we have:</p>
  
  <ul>
  <li>3 elements for the population</li>
  <li>10 NUM_CITIES for each element</li>
  <li>the total number of data for each array is 3*10=30</li>
  </ul>
  
  <p>The code require in input the numbers of the elements of a population, sets some coordinate in city_set arrays and create the global array with the coordinates x,y,and id of all the element of the entire population. </p>
  
  <pre><code>#include &lt;pthread.h&gt;
  
  #include &lt;limits&gt; // std::numeric_limits&lt;double&gt;
  #include &lt;iostream&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;sys/time.h&gt;
  #include &lt;utility&gt;
  //#include &lt;math.h&gt;
  #include &lt;algorithm&gt;    // std::lower_bound, std::find
  #include &lt;random&gt;
  #include &lt;cmath&gt; 
  #include &lt;cstring&gt;
  #include &lt;iomanip&gt;      // std::setprecision
  #include &lt;vector&gt;       // std::vector
  
  #define NUM_CITIES 10  // This is a tour for the LIN105. It has length 14379.
  // #define SIZE_POP 100000000
  #define SIZE_MATING 3
  #define MUTATION_RATE 0.03
  #define STALL_LIMIT 10
  
  // variabili condivise
  long size_pop = 0;
  long tot_elem = 0;
  const int num_threads = 24;
  int tid[num_threads];
  int start[num_threads];
  int stop[num_threads];
  
  // città
  int city_set_x[NUM_CITIES];
  int city_set_y[NUM_CITIES];
  int city_set_id[NUM_CITIES];
  
  // elementi della popolazione
  int *city_x;
  int *city_y;
  int *city_id;
  
  void *setup(void *p) {
  
      int id = *(int *)p;
      // std::cout &lt;&lt; "id: " &lt;&lt; id &lt;&lt; "\n";
  
      int s = start[id];
  
      int perm[NUM_CITIES];
      for(int i = 0; i &lt; NUM_CITIES; ++i) {
          perm[i] = i;
          // std::cout &lt;&lt; perm[i] &lt;&lt; ",";
      }
  
      for(long i = start[id]; i &lt; stop[id]; i += NUM_CITIES) {
          std::random_shuffle ( perm, perm + NUM_CITIES );
  
          for(int j = 0; j &lt; NUM_CITIES; ++j) {
              city_id[i + j] =  perm[j];
              city_x[i + j] =  city_set_x[perm[j]];
              city_y[i + j] =  city_set_y[perm[j]];
              // std::cout &lt;&lt; "(" &lt;&lt; city_x[i + j] &lt;&lt; "," &lt;&lt; city_y[i + j] &lt;&lt; ") ";
          }
          // std::cout &lt;&lt; "\n";
      }
  
  }
  
  
  static inline const double diffmsec(const struct timeval &amp; a, 
                                      const struct timeval &amp; b) {
      long sec  = (a.tv_sec  - b.tv_sec);
      long usec = (a.tv_usec - b.tv_usec);
  
      if(usec &lt; 0) {
          --sec;
          usec += 1000000;
      }
      return ((double)(sec*1000)+ (double)usec/1000.0);
  }
  
  int main(int argc, char *argv[]) {
  
      size_pop = atol(argv[1]);
  
      std::cout &lt;&lt; size_pop &lt;&lt; "\n";
  
      tot_elem = NUM_CITIES * size_pop;
      std::cout &lt;&lt; "tot_elem: " &lt;&lt; tot_elem &lt;&lt; "\n";
  
      struct timeval program_start, program_end, setup_start, setup_end;
  
      std::vector&lt;double&gt; v_set;
  
      city_x = (int *)malloc(tot_elem * sizeof(int));
      // memset(city_x, -1, tot_elem * sizeof(int));
      city_y = (int *)malloc(tot_elem * sizeof(int));
      // memset(city_y, -1, tot_elem * sizeof(int));
      city_id = (int *)malloc(tot_elem * sizeof(int));
      for(int i = 0; i &lt; tot_elem; ++i) {
          city_x[i] = -1;
          city_y[i] = -1;
          city_id[i] = -1;
      }
  
      srand(time(NULL));
  
      int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      int y[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
  
      // stampa
      std::cout &lt;&lt; "[CITTA.X]\n";
      for(int i = 0; i &lt; NUM_CITIES; ++i) {
  
          city_set_x[i] = x[i];
          // city_set[i].x = i + 1;
          std::cout &lt;&lt; city_set_x[i] &lt;&lt; " ";
      }
      std::cout &lt;&lt; "\n";
  
      std::cout &lt;&lt; "[CITTA.Y]\n";
      for(int i = 0; i &lt; NUM_CITIES; ++i) {
  
          city_set_y[i] = y[i];
          // city_set[i].y = i + 1;
          std::cout &lt;&lt; city_set_y[i] &lt;&lt; " ";
      }
      std::cout &lt;&lt; "\n";
  
      std::cout &lt;&lt; "[CITTA.ID]\n";
      for(int i = 0; i &lt; NUM_CITIES; ++i) {
  
          city_set_id[i] = i;
          std::cout &lt;&lt; city_set_id[i] &lt;&lt; " ";
      }
      std::cout &lt;&lt; "\n";
  
      // std::cin.get() != '\n';
  
      pthread_t threads[num_threads];
  
      for(int i = 0; i &lt; num_threads; ++i) {
          tid[i] = i;
          start[i] = i * NUM_CITIES * floor(size_pop/num_threads);
          // std::cout &lt;&lt; "start: " &lt;&lt; start &lt;&lt; "\n";
          if(i != num_threads - 1) {
              stop[i] = start[i] + (floor(size_pop/num_threads) * NUM_CITIES);
              // std::cout &lt;&lt; "stop: " &lt;&lt; stop &lt;&lt; "\n";
          }
          else {
              stop[i] = tot_elem;
              // std::cout &lt;&lt; "stop: " &lt;&lt; stop &lt;&lt; "\n";
          }
          // std::cout &lt;&lt; "\n";
      }
  
      for(int c = 0; c &lt; 10; c++) {
  
          gettimeofday(&amp;setup_start, NULL);
  
          for(int i = 0; i &lt; num_threads; ++i) {
              if( pthread_create( &amp;threads[i], NULL, &amp;setup, (void *) &amp;tid[i]) )
              {
                printf("Thread creation failed\n");
              }
          }
  
          for(int i = 0; i &lt; num_threads; ++i) {
              pthread_join( threads[i], NULL);
          }
  
          gettimeofday(&amp;setup_end, NULL);
          v_set.push_back(diffmsec(setup_end, setup_start) / 1000);
      }
  
      // // stampa
      // std::cout &lt;&lt; "[SETUP]\n";
      // for(int i = 0; i &lt; size_pop; ++i){
      //  long idx = i * NUM_CITIES;
      //  std::cout &lt;&lt; "pop[" &lt;&lt; i &lt;&lt; "]: ";
      //  for(int j = 0; j &lt; NUM_CITIES; ++j){
      //      std::cout &lt;&lt; "(" &lt;&lt; city_x[idx + j] &lt;&lt; "," &lt;&lt; city_y[idx + j] &lt;&lt; ") ";
      //  }
      //  std::cout &lt;&lt; "\n";
      // }
  
      double sum = 0;
      double mean;
  
  
      sum = 0;
      for (int i = 0; i &lt; v_set.size(); ++i) {
          sum += v_set[i];
      }
      mean = sum / v_set.size();
      std::cout &lt;&lt; "[SET]: " &lt;&lt; mean &lt;&lt; " s\n";
  
      free(city_x);
      free(city_y);
      free(city_id);
  
  }
  </code></pre>
  
  <p>I run the code with <strong>1000000 elemets</strong> setting the number of thread to 1 and the <strong>result is 0.332 s</strong>.
  After running with <strong>1000000 elemets</strong> but setting the number of threads to 4 the <strong>result is 1.361 s</strong>.
  If I <strong>increment the number at 24</strong> the <strong>result is 0.60 s</strong> but is twice the sequential!
  When I go over the 24 number of threads the result stay that or increment again.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Using: <strong>grep -c processor /proc/cpuinfo</strong></p>
  
  <p>I obtain 56.</p>
  
  <p>Using: <strong>cat /proc/cpuinfo</strong></p>
  
  <p>processor   : 0</p>
  
  <p>vendor_id   : GenuineIntel</p>
  
  <p>cpu family  : 6</p>
  
  <p>model       : 79</p>
  
  <p>model name  : Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz
  stepping    : 1</p>
  
  <p>microcode   : 0xb00001e</p>
  
  <p>cpu MHz     : 1967.906</p>
  
  <p>cache size  : 35840 KB</p>
  
  <p>physical id : 0</p>
  
  <p>siblings    : 28</p>
  
  <p>core id     : 0</p>
  
  <p>cpu cores   : 14</p>
  
  <p>apicid      : 0</p>
  
  <p>initial apicid  : 0</p>
  
  <p>fpu     : yes</p>
  
  <p>fpu_exception   : yes</p>
  
  <p>cpuid level : 20</p>
  
  <p>wp      : yes</p>
  
  <p>flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch arat epb pln pts dtherm intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local</p>
  
  <p>bogomips    : 4799.62</p>
  
  <p>clflush size    : 64</p>
  
  <p>cache_alignment : 64</p>
  
  <p>address sizes   : 46 bits physical, 48 bits virtual</p>
  
  <p>for each of the 56 processors.</p>