00001
00002
00003
00004
00005 #include <omp.h>
00006 #include <stdio.h>
00007 #include <string.h>
00008
00009 int cnt;
00010 #pragma omp threadprivate (cnt)
00011
00012 void
00013 nqueens (char *a, int n, int pos)
00014 {
00015
00016 char b[pos + 1];
00017 int i, j;
00018 memcpy (b, a, pos);
00019 for (i = 0; i < n; i++)
00020 {
00021 for (j = 0; j < pos; j++)
00022 if (b[j] == i || b[j] == i + pos - j || i == b[j] + pos - j)
00023 break;
00024 if (j < pos)
00025 continue;
00026 if (pos == n - 1)
00027
00028 ++cnt;
00029 else
00030 {
00031 b[pos] = i;
00032 #pragma omp task
00033 nqueens (b, n, pos + 1);
00034 }
00035 }
00036 }
00037
00038 int
00039 main (int argc, char **argv)
00040 {
00041 int n = 8;
00042 if (argc >= 2)
00043 n = strtoul (argv[1], NULL, 0);
00044 if (n < 1 || n > 127)
00045 {
00046 fprintf (stderr, "invalid count %d\n", n);
00047 return 1;
00048 }
00049 cnt = 0;
00050 double stime = omp_get_wtime ();
00051 nqueens ("", n, 0);
00052 printf ("serial N %d solutions # %d time %f\n", n, cnt, omp_get_wtime () - stime);
00053 #pragma omp parallel
00054 cnt = 0;
00055 stime = omp_get_wtime ();
00056 int tempcnt = 0;
00057 #pragma omp parallel reduction (+:tempcnt)
00058 {
00059 #pragma omp single
00060 nqueens ("", n, 0);
00061 tempcnt = cnt;
00062 }
00063 cnt = tempcnt;
00064 printf ("parallel N %d solutions # %d time %f\n", n, cnt, omp_get_wtime () - stime);
00065 return 0;
00066 }