首先,我使用 python 脚本生成 600 个文件,例如:one0 ...one199 two0...two199 Five0...five199 然后我编写了一个 C++ 程序,它使用 fstream 来读取不同的文件。我的代码:
int main(int argc,char* argv[])
{
init();//init the data structure
int createthread=0;
signal(SIGINT,CtrlHandlerRoutine);
pthread_t *workthread= new pthread_t[6];
ThreadParam *param=new ThreadParam[6];
for (int i = 0; i < 6; ++i)
{
param[i].thread_index=i;
}
for (int index = 0; index < 2; ++index)
{
/* code */
if(pthread_create(&workthread[index],NULL,WorkerThreadFunction,¶m[index])==0)
{
createthread++;
fflush(stdout);
}
}
while(!gExitFlag)
{
usleep(100000);
}
gWorkThreadStopFlag=true;
while(gStoppedThread<createthread)
{
usleep(1);
}
delete[] workthread;
for(int i=0; i<DELAY_TYPE_NUM; i++)
{
printProcDelayResult(gProcDelay[i]);
}
fflush(stdout);
return 0;
}
线程函数:
void* WorkerThreadFunction(void* arg)
{
ThreadParam *param=(ThreadParam*) arg;
int threadnum=param->thread_index;
int max_index,min_index;
int protype=0;
string filetype="";
//memset(&sessionProcDelay,0,21*sizeof(sessionProcDelay)); init the data structure
//fstream fd;//define a handle of the file
switch(threadnum)
{
case 0:
max_index=99;
min_index=0;
protype=1;
filetype="one";
break;
case 1:
max_index=199;
min_index=100;
protype=1;
filetype="one";
break;
case 2:
max_index=99;
min_index=0;
protype=2;
filetype="two";
break;
case 3:
max_index=199;
min_index=100;
protype=2;
filetype="two";
break;
case 4:
max_index=99;
min_index=0;
protype=3;
filetype="five";
break;
case 5:
max_index=199;
min_index=100;
protype=3;
filetype="five";
break;
}
for (int i = min_index; i <=max_index; ++i)
{
ostringstream oss;
oss<<i;
string filename=filetype+oss.str();
fstream fd(filename.c_str(),ios::in);
if(!fd.is_open())
{
printf("Can not open the file\n");
}
int num=0;
char text[6];
while(!fd.eof())
{
num++;
fd.getline(text,6);
string line(text);
int mvalue=atoi(line.c_str());
f_StatProcessDelay(sessionProcDelay[i*DELAY_TYPE_NUM],protype,mvalue);
/*if(mvalue==0)
{
printf("filename:%s,line:%d content %s\n",filename.c_str(),num,line.c_str());
}*/
}
fd.close();
}
printf("OVER\n");
while(!gWorkThreadStopFlag)
{
usleep(1000);
}
pthread_mutex_lock(&gDataLock);
for (int j = 0; j < 100; ++j)
{
for (int k = 0; k < DELAY_TYPE_NUM; ++k)
{
/* code */
if(sessionProcDelay[j*DELAY_TYPE_NUM+k].procDelayMax>0) // if process delay data is available, if not procDelayMax is -1
{
int procTypeIndex = sessionProcDelay[j*DELAY_TYPE_NUM+k].procDelayType;
updateTotalProcDelay(sessionProcDelay[j*DELAY_TYPE_NUM+k], gProcDelay[procTypeIndex-1]);
}
}
}
gStoppedThread++;
pthread_mutex_unlock(&gDataLock);
}
和 GDB 日志:
(gdb) bt
#0 0x00007ffff7935d1d in std::basic_istream<char, std::char_traits<char> >::getline(char*, long) () from /usr/lib64/libstdc++.so.6
#1 0x0000000000401db6 in WorkerThreadFunction (arg=0x604054) at mutithreadcal.cpp:147
#2 0x00007ffff7bc85f0 in start_thread () from /lib64/libpthread.so.0
#3 0x00007ffff71bf84d in clone () from /lib64/libc.so.6
#4 0x0000000000000000 in ?? ()
这个段错误的根本原因是什么?