C中的迷宫生成Openmp

时间:2018-05-06 10:00:31

标签: c openmp

我有一个用于迷宫生成的C代码,我想使用Openmp来并行化它。我不明白该怎么做。如果我将循环中的所有变量设置为私有,它甚至不起作用。我不明白从属线程将如何开始。主线程具有初始化以开始。我可以折叠嵌套的for循环吗?并行化的新手。

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

int main() {

  clock_t start, end;
  double cpu_time_used;
  int width, height;
  int *maze;
  start = clock();
  printf("enter maze width\n");
  scanf("%d", &width);
  printf("enter maze height\n");
  scanf("%d", &height);
  width = width *2 +1;
  height = height*2 +1;

  /* Validate the size. */
  if(width < 7 || height < 7) {
    printf("error: illegal maze size\n");
    exit(EXIT_FAILURE);
  }

  /* Allocate the maze array. */
  maze = (int*)malloc(width * height * sizeof(char));



  /* Initialize the maze. */
  int x, y;
  for(x = 0; x < width * height; x++) {
    maze[x] = 1;
  }
  maze[1 * width + 1] = 0;

  /* Seed the random number generator. */
  srand(time(0));

  /* Carve the maze. */
  int x1, y1;
  int x2, y2;
  int dx, dy;
  int dir, count;

  /* Set up the entry and exit. */
  maze[0 * width + 1] = 0;
  maze[(height - 1) * width + (width - 2)] = 0;

  #pragma omp parallel for
  for(y = 1; y < height; y += 2) {
    for(x = 1; x < width; x += 2) {

      dir = rand() % 4;
      count = 0;
      while(count < 4) {
        dx = 0; dy = 0;
        switch(dir) {
        case 0:  dx = 1;  break;
        case 1:  dy = 1;  break;
        case 2:  dx = -1; break;
        default: dy = -1; break;
        }
        x1 = x + dx;
        y1 = y + dy;
        x2 = x1 + dx;
        y2 = y1 + dy;
        if(   x2 > 0 && x2 < width && y2 > 0 && y2 < height
            && maze[y1 * width + x1] == 1 && maze[y2 * width + x2] == 1) {
          maze[y1 * width + x1] = 0;
          maze[y2 * width + x2] = 0;
          x = x2; y = y2;
          dir = rand() % 4;
          count = 0;
        } else {
          dir = (dir + 1) % 4;
          count += 1;
        }
      }
    }
  }

  /* Display the maze. */
  /* Graphical view. */
  printf("\n\nMaze in graphical form \n\n");
  for(y = 0; y < height; y++) {
    for(x = 0; x < width; x++) {
      if(maze[y * width + x]){
        printf("##");
      }
      else{
        printf("  ");
      }
    }
    printf("\n");
  }
  /* Matrix View */
  printf("\n\nMaze in matrix form: 0s = wall, 1s =space\n\n");
  for(y = 0; y < height; y++) {
    for(x = 0; x < width; x++) {
      printf("%i ",!maze[y * width + x]);
    }
    printf("\n");
  }

  /* Clean up. */
  free(maze);
  end = clock();
  cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
  printf("\ntime taken by program(in milliseconds) to run is %f\n\n",cpu_time_used*1000);

}

0 个答案:

没有答案
相关问题