2

我试图让多个线程对二维数组执行并行计算。用户在 25*25 2d 数组上指定他们想要多少线程,如果用户想要 5 个线程,那么每个线程对 125 个元素执行计算。(为简单起见,我对这些数字进行了硬编码,只是为了让程序在这些条件下工作)。

该代码适用于 1 个线程,当我使用 for 循环进行模拟时,一切正常。这是康威人生游戏节目。使用 1 个线程或 forloop 调用 gen 函数 5 次,程序可以正常工作。它正确打印出网格。有 5 个线程,它只打印一次,程序结束

我无法在线程内部进行测试,因为 printf 在线程中不起作用。我已经花了几个小时在这上面,但我无法弄清楚。

int N; 
int **gridA;// odd generations
int **gridB;//even
int T = 5;//number of threads

int main ( int argc, char *argv[] ){
  int i,j;
  const int STACK_SIZE = 65536;
  char *stack;
  char *stackTop[t];
  pid_t cret[t], wret;
  N = 25;//array size [25][25];
  //initialize stack
   stack = malloc(STACK_SIZE);
  for(i = 0; i < T; i++){
    stackTop[i] = stack + STACK_SIZE;
  }

//initilize arrays and load gridA with input

    while(1){}
      for(i=0; i < T; i++) cret[i]=clone(generateNext, stackTop[i], CLONE_VM|SIGCHLD, (void*)i);//thread code
      for(i=0; i < T; i++) waitpid(cret[i],&status,0);//wait for threads to finish       

   //for(i=0; i < T; i++){generateNext((void*)i);} Simulate threads, works like this
    if(toggle){//grids used interchangeably. 
  print_array(gridA);
        toggle = 0;
    } else {
        print_array(gridB);
        toggle = 1;
    }
  }
}

//figures out the next generation
void generateNext(void *p){
//finds out the two points each thread will calculate for by using p
//eg first thread: gridA[0][24] to [4][24] 2nd thread: [5][25] to 9[25]
//then finds neighbours and changes state of each element accordingly

}
4

1 回答 1

0

while(1){}是个坏主意。请提供实际导致问题的代码。

也就是说clone()waitpid()并不是真正用于多线程,而是用于多处理。由于进程具有单独的内存空间,因此这是行不通的。请查看任何 pthread 教程,让您开始使用多线程。

于 2015-02-20T22:47:11.513 回答