C ++ pthreads,主要功能提前停止运行

时间:2013-12-27 21:52:08

标签: c++ multithreading pthreads main

我正在制作我的第一个多线程程序并遇到一些问题。我将代码基于我在网上找到的一个例子,它在我做出改变之前一直运行良好。下面的主要功能使多个线程运行另一个功能。该函数运行我写的另一个c ++程序的实例,工作正常。问题是程序创建所有线程后,它会停止运行。其他线程继续运行并正常工作,但主线程停止,甚至没有打印出我给它的cout语句。例如,如果我运行它,则输出为:

Enter the number of threads:
// I enter '3' 
main() : creating thread, 0
this line prints every time
main() : creating thread, 1
this line prints every time
main() : creating thread, 2
this line prints every time

然后是我的其他程序的所有输出,该程序运行3次。但主要功能从未打印出“此行永不打印出来”。我确信我对线程如何运作存在一些根本性的误解。

#include <iostream>
#include <stdlib.h>
#include <cstdlib>
#include <pthread.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include <unistd.h>

using namespace std;

struct thread_data{
   int  thread_id;
};

void *PrintHello(void *threadarg)
{
   struct thread_data *my_data;

   my_data = (struct thread_data *) threadarg;

   stringstream convert;
   convert << "./a.out " << my_data->thread_id << " " << (my_data->thread_id+1) << " " << my_data->thread_id;
   string sout = convert.str(); 
   system(sout.c_str());

   pthread_exit(NULL);
}

int main ()
{
   int NUM_THREADS;

   cout << "Enter the number of threads:\n";
   cin >> NUM_THREADS;

   pthread_t threads[NUM_THREADS];
   struct thread_data td[NUM_THREADS];
   int i;

   for( i=0; i < NUM_THREADS; i++ ){
      cout <<"main() : creating thread, " << i << endl;
      td[i].thread_id = i;
      pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);
      cout << endl << "this line prints every time" << endl;
   }

   cout << endl << "This line is never printed out";

   pthread_exit(NULL);
}

1 个答案:

答案 0 :(得分:0)

这是因为你没有使用pthread_join(threads[i],NULL)pthread_join()阻止main在线程完成执行之前结束