我一直在使用一个程序,该程序将读取多个文本文件,记录其中的单词数,并将所有单词及其频率写入文件。但是,我在代码中的某个地方遇到了分段错误。我曾尝试使用Valgrind之类的工具来帮助我调试它,但它只指向我在主循环中说__typeof(self) __weak weakSelf = self;
的位置。我为发布我的大部分代码而道歉,但我花了好几个小时试图找到错误的位置,似乎无法在我的生活中找到它。当我开始在pthread_exit()中传递结构时,问题就开始了。
int i = 0
答案 0 :(得分:0)
这些是使程序正常运行所需的更改。
1)一个问题似乎是函数线程中变量的大小。看起来每个生成的线程都有一些默认限制。你可以阅读pthread_attr_setstacksize。但最简单的解决方案是减少线程中字符串的大小。因此,变量的大小就是调用线程函数后它给出分段错误的原因。 正如上面的评论中已经提到的那样,使用vector / maps类将有助于减少对大型局部变量的需求。
2)返回变量必须是非局部变量,否则返回值不会使其成功返回。
3)刚注意到主循环(变量a)只运行一次。一旦线程启动(pthread_create),循环就会等待连接。这将导致线程的序列化。可以先完成创建,然后可以在之后的单独循环中调用连接。
下面给出了变化..
在函数 - 线程
中 info *information;
//changed to pointer
// info information;
char *fileName = (char *)arg;
ifstream myfile (fileName);
string line;
string fullText[1500];
string dictionary[5000];
// reduced size
//string fullText[15000];
//string dictionary[500000];
.....
information = new info; // create an instance
........
// change to pointer
information->dictionary[i] = dictionary[i];
}
// Sets words equal to word count and then passes the structure information out of the thread
information->words = wordCount;
pthread_exit(information); // return pointer
in function - main
info *information; // change to pointer
...
for(a = 0; a < 2; ++a){ // loop to 2
.....
pthread_create(&threadCount[a], NULL, threads, (void *)fileName); // changed file name
// pthread_create(&threadCount[a], NULL, threads, &fileName);
wordCount = information->words; // changed for pointer
...
dict[b] = information->dictionary[b] // changed for pointer
编辑完成后,您应该能够运行以调试其余功能。