在同一个循环中创建/加入pthread

时间:2018-05-29 21:57:38

标签: c multithreading parallel-processing pthreads

我有一个名为doneArray的数组,我在线程完成时存储了1。例如,在我调用pthread_exit之前的线程4中,我将doneArray [4]设置为1.所以我可以运行doneArray来查看给定的线程是否已经完成。

在我的main()代码的这个循环中,我创建了一个线程,然后检查是否有任何线程已经完成。如果他们这样做,我加入他们。由此产生的行为有时是疯狂的,并且不像我有一个单独的连接循环一样工作。

   for(long i = 0; i < numberOfThreads; i++){

      pthread_create(&threads[i], NULL, body, (void*) i);

      sleep(random() % 5 + 1);

      //the loop that creates new threads should join threads that have finished
      for(int j = 0; j < numberOfThreads; j++){
         if(doneArray[j] == 1){
            pthread_join(threads[j], &retval);
         }
      }

   }

我的导师告诉我们在同一循环中执行pthread_createpthread_join,否则我们会失分。我很困惑,因为我以前被教过不要这样做,我在这个网站上看到的其他答案也说过要在一个单独的循环中进行连接:

If we put the pthread_join() in the same loop with pthread_create(), the calling thread i.e. main() will wait for the thread 0 to finish its work before creating the thread 1. This would force the threads to execute sequentially, not in parallel. Thus it would kill the purpose of multi-threading.

0 个答案:

没有答案