C++pthreads,主函数提前停止运行



我正在制作我的第一个多线程程序,但遇到了一些问题。我根据我在网上找到的一个例子编写了代码,在我做出更改之前,这个例子一直很好。下面的主函数生成多个线程,这些线程运行另一个函数。该函数运行我编写的另一个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);
}

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

最新更新