title: How to parallelize my n queen puzzle with Pthreads?
body: <p>I have the following Pthreads code for n-queen puzzle. It compiles successfully, but I get wrong answer. Whatever value I type I get as an answer zero. I guess I have some kind of logic error in my code. I guess the problem happens somewhere in backtracking/recursion part. If someone could suggest me a solution, I would be glad.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;time.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;assert.h&gt;
  
  int NTHREADS, SIZE; 
  int *hist;
  int count = 0;
  
  int solve(int col, int tid)
  {
      int start = tid * SIZE/NTHREADS;
      int end = (tid+1) * (SIZE/NTHREADS) - 1;
      int i, j;
      if (col == SIZE) 
      {
          count++;
      }
  
      #define attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j)
      for (i = start; i &lt;= end; i++) {
          for (j = 0; j &lt; col &amp;&amp; !attack(i, j); j++);
          if (j &lt; col) continue;
  
          hist[col] = i;
          solve(col + 1, tid);
      }
  
      return count;
  }
  
  void *worker(void *arg)
  {
      int tid = (int)arg;
      solve(0, tid);
  }
  
  int main(int argc, char* argv[])
  {
      pthread_t* threads;
      int rc, i;
  
      // checking whether user has provided the needed arguments
      if(argc != 3)
      {
          printf("Usage: %s &lt;number_of_queens&gt; &lt;number_of_threads&gt;\n", argv[0]);
          exit(1);
      }
  
  
      // passing the provided arguments to the SIZE and NTHREADS 
      // variable, initializing matrices, and allocating space 
      // for the threads
      SIZE = atoi(argv[1]);
      NTHREADS = atoi(argv[2]);
      threads = (pthread_t*)malloc(NTHREADS * sizeof(pthread_t));
      hist = (int*)malloc(SIZE * sizeof(int));
  
      // declaring the needed variables for calculating the running time
      struct timespec begin, end;
      double time_spent;
  
      // starting the run time
      clock_gettime(CLOCK_MONOTONIC, &amp;begin);
  
      for(i = 0; i &lt; NTHREADS; i++) {
          rc = pthread_create(&amp;threads[i], NULL, worker, (void *)i);
          assert(rc == 0); // checking whether thread creation was successful
      }
  
      for(i = 0; i &lt; NTHREADS; i++) {
          rc = pthread_join(threads[i], NULL);
          assert(rc == 0); // checking whether thread join was successful
      }
  
      // ending the run time
      clock_gettime(CLOCK_MONOTONIC, &amp;end);
  
      // calculating time spent during the calculation and printing it
      time_spent = end.tv_sec - begin.tv_sec;
      time_spent += (end.tv_nsec - begin.tv_nsec) / 1000000000.0;
      printf("Elapsed time: %.2lf seconds.\n", time_spent);
  
      printf("\nNumber of solutions: %d\n", count);
  
      free(hist);
      return 0;
  
  }
  </code></pre>