【问题标题】:Nqueens with openmp cNqueens 与 openmp c
【发布时间】:2013-09-06 00:05:03
【问题描述】:

我正在用open mp解决n皇后问题,

(最初的八皇后问题包括试图找到一种方法将八个皇后放在棋盘上,这样任何皇后都不会攻击任何其他皇后。表达问题的另一种方式是将八个“任何东西”放在一个八由八个网格组成,这样它们都不共享同一行、列或对角线。)

如果您查看我尝试使用 #pragma omp task 的代码,但似乎进入了永远循环,您将如何在 solve(int Queens[]) 函数中使用 omp 任务?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <omp.h>

#define N  15
#define MAXThreads 2

int solutions;

int put(int Queens[], int row, int column)
{
  int i;
    //#pragma for schedule(static) 
    for(i=0; i<row; i++) {
        if (Queens[i] == column  || abs( Queens[i]-column ) == ( row-i ) )  
            return -1;
   }
    Queens[row]=column; 
    if(row==N-1) {
        #pragma omp critical
        {
        solutions++;
        }        
    }else{
        for(i=0; i<N; i++) { // increment row
            put(Queens, row+1, i);
        }
    }
 return 0;
}


void solve(int Queens[]) {
    int i;
    #pragma omp parallel private(Queens) num_threads(MAXThreads)
    {
//      #pragma omp single
//      {
            #pragma omp for schedule(static)
            for(i=0; i<N; i++) {
//              #pragma omp task
                put(Queens, 0, i);
//             }
            }
    }

}



int main()
{
    int Queens[N];
    time_t t0=0, tf=0,t0s=0,tfs=0;              
//------------------------------------------
    t0 = time(NULL);
//------------------------------------------
        //solve_secuencial(Queens);
    solve(Queens);
 //------------------------------------------
    tf = time(NULL);
//------------------------------------------
        printf( "# solutions %d time: %f \n",solutions, difftime(tf, t0));

 return 0;

}

【问题讨论】:

    标签: c parallel-processing openmp


    【解决方案1】:

    自从我上次使用 OpenMP 已经有一段时间了,但我相信 private(p),其中 p 是一个指针(或数组参数)只会使 指针,而不是数据指向,私人。所以数组本身仍然是共享的。见this question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2017-01-19
      • 2021-08-10
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多