【发布时间】:2014-01-15 11:54:46
【问题描述】:
我正在制作我的第一个多线程程序,但遇到了一些问题。我的代码基于我在网上找到的一个示例,在我进行更改之前它运行良好。下面的 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);
}
【问题讨论】:
-
你没有刷新缓冲区。
-
所以我需要在我的其他线程中使用 cout
-
谢谢!它有效,我现在明白发生了什么。
标签: c++ multithreading pthreads main