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