title: Peterson's Algorithm in C for Thread concurrency (segment fault)
body: <p>Hey guys I'm implementing Peterson's algorithm in C. I have two functions that will be executed by the threads created, one that adds 1 to a variable and other that subtracts 1 to that same variable.</p>
  
  <p>The program receives an argument of type int, that integer is the square root of the number of threads I want to create, for example if I execute it in the terminal typing 
  ./algorithm 10, there will be 10*10 (10 000) threads created.</p>
  
  <p>The program runs ok if y type less than 170 as an argument (There would be 28900 threads created) but if I want to create more than that I got a segment fault, tried using "long long int" variables but that wasn't it. </p>
  
  <p>There is a counter named "cont", the variable will be printed each time cont reaches 10 000.
  There is another print for the last result of the variable, that should always be 0 because n threads added 1 and n threads subtracted 1.</p>
  
  <p>I want to know why I'm getting a Segment Fault, if there is a limit of threads to be created, or if it is something in my code.</p>
  
  <p>I'm running it using the next command to use only one processor cause Peterson's algorithm only work perfectly on mono-processor systems:</p>
  
  <pre><code>taskset -c 0 ./alg3 100
  </code></pre>
  
  <p>Here's the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  
  
  
  
  long int n;
  long int var = 0;
  long int cont = 1;
  int flag[] = {0, 0};
  int turn = 0;
  
  void* sum(void* data) {
      //int n = *((int*)data); 
      int i;
  
      turn = 2;
      flag[0] = 1;
      while (turn == 2 &amp;&amp; flag[1]);
      cont++;
      var += 1;
      if (cont == 10000) {
          printf("varsum=%ld\n", var);
          cont = 1;
      }
  
      flag[0] = 0;
  }
  
  void* rest(void* data) {
      //int n = *((int*)data); 
      int i;
      turn = 1;
      flag[1] = 1;
      while (turn == 1 &amp;&amp; flag[0]);
      cont++;
      var -= 1;
      if (cont == 10000) {
          printf("varres=%ld\n", var);
          cont = 1;
      }
  
      flag[1] = 0;
  
  }
  
  main(int argc, char *argv[]) {
      long int i;
      n = atoi(argv[1]);
      n *= n; //n*n is the actual number of threads that will be created
  
      pthread_t tid[n];
  
  
      for (i = 0; i &lt; n; i++) {
          pthread_create(&amp;tid[i], NULL, sum, NULL);
          //cont++;
  
      }
      for (i = 0; i &lt; n; i++)
          pthread_join(tid[i], NULL);
  
      for (i = 0; i &lt; n; i++) {
          pthread_create(&amp;tid[i], NULL, rest, NULL);
          //cont++;
  
      }
      for (i = 0; i &lt; n; i++)
          pthread_join(tid[i], NULL);
  
      printf("main() reporting that all %ld threads have terminated\n", i);
      printf("variable=%ld\n", var);
  
  } /* main */
  </code></pre>