nqueens-1.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* { dg-do run } */
  2. /* { dg-options "-O2 -fopenmp" } */
  3. /* { dg-require-effective-target tls_runtime } */
  4. #include <omp.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <stdlib.h>
  8. int cnt;
  9. #pragma omp threadprivate (cnt)
  10. void
  11. nqueens (char *a, int n, int pos)
  12. {
  13. /* b[i] = j means the queen in i-th row is in column j. */
  14. char b[pos + 1];
  15. int i, j;
  16. memcpy (b, a, pos);
  17. for (i = 0; i < n; i++)
  18. {
  19. for (j = 0; j < pos; j++)
  20. if (b[j] == i || b[j] == i + pos - j || i == b[j] + pos - j)
  21. break;
  22. if (j < pos)
  23. continue;
  24. if (pos == n - 1)
  25. /* Found a solution. Could output it here. */
  26. ++cnt;
  27. else
  28. {
  29. b[pos] = i;
  30. #pragma omp task
  31. nqueens (b, n, pos + 1);
  32. }
  33. }
  34. }
  35. int
  36. main (int argc, char **argv)
  37. {
  38. int n = 8;
  39. if (argc >= 2)
  40. n = strtoul (argv[1], NULL, 0);
  41. if (n < 1 || n > 127)
  42. {
  43. fprintf (stderr, "invalid count %d\n", n);
  44. return 1;
  45. }
  46. cnt = 0;
  47. double stime = omp_get_wtime ();
  48. nqueens ("", n, 0);
  49. printf ("serial N %d solutions # %d time %f\n", n, cnt, omp_get_wtime () - stime);
  50. #pragma omp parallel
  51. cnt = 0;
  52. stime = omp_get_wtime ();
  53. int tempcnt = 0;
  54. #pragma omp parallel reduction (+:tempcnt)
  55. {
  56. #pragma omp single
  57. nqueens ("", n, 0);
  58. tempcnt = cnt;
  59. }
  60. cnt = tempcnt;
  61. printf ("parallel N %d solutions # %d time %f\n", n, cnt, omp_get_wtime () - stime);
  62. return 0;
  63. }