2

我正在学习pthread,以下是我的简单代码:

  1 #include <pthread.h>
  2 #include <cstdlib>
  3 #include <iostream>
  4 #include <string>
  5 #include <sstream>
  6
  7 using namespace std;
  8
  9 struct ThreadParam
 10 {
 11     int thread_id;
 12     string message;
 13 };
 14
 15 string int2string(int i)
 16 {
 17     stringstream s;
 18     s << i;
 19     return s.str();
 20 }
 21
 22 void * Hello(void * param)
 23 {
 24     ThreadParam * threadParam = (ThreadParam*)param;
 25
 26     int tid = threadParam->thread_id;
 27     string msg = threadParam->message;
 28     string output = msg + " In thread " + int2string(tid);
 29
 30     cout << output << endl;
 31     pthread_exit(NULL);
 32 }
 33
 34 int main()
 35 {
 36     const int count = 30;
 37     ThreadParam params[count];
 38
 39     pthread_t threads[count];
 40     int rc;
 41     for(int t=0; t < count; t++)
 42     {
 43         cout << "In main: creating thread " << t << endl;
 44
 45         params[t].thread_id = t;
 46         params[t].message = "Hello " + int2string(t) + "!";
 47
 48         rc = pthread_create(&threads[t], NULL, Hello, (void*)&params[t]);
 49
 50         if(rc)
 51         {
 52             cout << "Error! Return code is " << rc << endl << flush;
 53             exit(-1);
 54         }
 55     }
 56     pthread_exit(NULL);
 57 }

创建最后一个线程后出现分段错误。输出是:

In main: creating thread 0
In main: creating thread 1
In main: creating thread 2
In main: creating thread 3
In main: creating thread 4
In main: creating thread 5
In main: creating thread 6
In main: creating thread 7
In main: creating thread 8
In main: creating thread 9
In main: creating thread 10
In main: creating thread 11
Hello 0! In thread 0
Hello 1! In thread 1
Hello 2! In thread 2
Hello 3! In thread 3
Hello 4! In thread 4
In main: creating thread 12
In main: creating thread 13
In main: creating thread 14
In main: creating thread 15
In main: creating thread 16
In main: creating thread 17
In main: creating thread 18
In main: creating thread 19
In main: creating thread 20
In main: creating thread 21
In main: creating thread 22
In main: creating thread 23
In main: creating thread 24
In main: creating thread 25
In main: creating thread 26
In main: creating thread 27
In main: creating thread 28
In main: creating thread 29
Segmentation fault

我不知道为什么,有什么线索吗?

4

3 回答 3

3

查看您的代码,我可以告诉您,在创建最后一个线程后,您会破坏主线程(“创建者”线程)。这导致该线程的堆栈被释放。但是因为您使用指向主线程堆栈内存的指针(ThreadParam params[count];准确地说;您将指向它的指针传递给pthread_create函数)然后您尝试读取其他线程中的无效数据。在主线程销毁后,为主线程堆栈分配的内存页面被标记为“未使用”或“未分配”,因此您在尝试访问它们时会遇到段错误。

UPD:正如其他人所说,您应该使用pthread_join函数等待所有线程完成然后销毁主线程。

于 2012-09-13T20:58:15.907 回答
2

在退出程序之前,您必须等待线程完成。如果你不这样做——可能会发生很多坏事。要加入线程,请使用pthread_join(). 您还可能在 API 文档中遇到“分离”线程——不要费心尝试使用它,它不起作用,至少在 Linux 中不起作用。

除此之外——调试器是最好的人选来告诉你的进程为什么会出现段错误,可能有很多原因,猜测在这方面没有帮助。

于 2012-09-13T20:52:54.203 回答
2

您的主线程应该等到您的辅助线程完成执行。这导致了段错误。

主线程应该加入其他线程。

于 2012-09-13T20:55:20.510 回答