【问题标题】:C++ pthreads, main function stops running earlyC++ pthreads,主函数提前停止运行
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    相关资源
    最近更新 更多