简体   繁体   English

不能使用多线程,但可以使用for循环或单线程

[英]Can't multithread but works with a for loop or single thread

I'm trying to get multiple threads to perform parallel calculations on a 2D array. 我正在尝试让多个线程在2D数组上执行并行计算。 The user specifies how many threads they want so on a 25*25 2d array if the user wants 5 threads then each thread performs calculation on 125 elements. 如果用户需要5个线程,则用户在25 * 25 2d数组上指定所需的线程数,然后每个线程对125个元素执行计算。 (for simplicity I hardcoded these number just to try and get program to work under these conditions). (为简单起见,我对这些数字进行了硬编码,只是试图使程序在这些条件下可以工作)。

The code works for 1 thread and when I simulated with a for loop everything works correctly. 该代码适用于1个线程,而当我使用for循环进行仿真时,一切正常。 It's a conways game of life program. 这是一个康威人生游戏程序。 With 1 thread or forloop calling gen function 5 times the programs works fine. 用1个线程或forloop调用gen函数5次,程序运行正常。 It prints out the grids properly. 它将正确打印出网格。 With 5 threads it just prints out once and program ends 它有5个线程,仅打印一次,程序结束

I can't test inside the threads because printf doesn't work in threads. 我无法在线程内部进行测试,因为printf在线程中不起作用。 I've spent hours on this and I can't figure it out. 我已经花了几个小时,我无法弄清楚。

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

}

while(1){} is a bad idea. while(1){}是个坏主意。 Please provide the code that actually causes problems. 请提供实际导致问题的代码。

That said clone() and waitpid() are not really for multithreading but for multiprocessing. 那就是说clone()waitpid()并不是真正用于多线程,而是用于多重处理。 Since processes have separate memory spaces, this can't work. 由于进程具有单独的内存空间,因此无法使用。 Please check out any pthread tutorial to get you started with multithreading. 请查看任何pthread教程以开始使用多线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM