我的代码让我发疯,因为它有时工作正常,但有时会出现核心转储或分段错误或双重免费(faststop)错误。 我认为这是因为某些线程无法创建,但我无法创建它。这段代码有什么问题? 此代码应该在存储在路径中的文本文件中找到\ n。
以下是代码:
这是Search_inp struct
typedef struct Search_inp{
string * path;
string * phrase;
int a ;
int b;
int file_size;
vector<int>* vec;
}search_inp;
这个函数应该返回一个void *
指向结构的指针,该结构包含我要传递给线程的数据!
void * make_search_inp(string & path , string & phrase , int a , int b , int file_size , vector<int>&vec){
search_inp * res = (search_inp*)malloc(sizeof(search_inp));
res->path = &path;
res->phrase = & phrase;
res->a = a;
res->b = b;
res -> file_size = file_size;
res->vec = &vec;
return (void *)res;
}
此功能将开始在文件
中搜索\ n// this function will multi thread the search of \n's and do this through search func
void find_backslash(string path , vector<int> &place_backslash , int file_size){
int counter = 0;
string backslash = "\n";
vector<void*>temp;
vector<pthread_t> tid;
pthread_t t;
while(counter * range <= file_size ){
temp.push_back( make_search_inp(path , backslash , counter*range , (counter+1)*range-1 , file_size , place_backslash ));
pthread_create(&t, NULL , search , temp.back() );
tid.push_back(t);
counter++;
}
for(int i = 0 ; i<tid.size() ;i++) pthread_join(tid[i] , NULL);
//when the erorr happend program can not reach this place...
while(tid.size()) tid.pop_back();
while(temp.size()) temp.pop_back();
sort(place_backslash.begin() , place_backslash.end());
}
这是我的代码的搜索功能:
void* search(void * temp){
search_inp* Stemp = (search_inp*)temp;
string path = *(Stemp->path);
string phrase = *(Stemp->phrase);
int a = Stemp->a;
int b = Stemp->b;
int file_size = Stemp->file_size;
vector<int>&vec = *(Stemp->vec);
if(path == "" ) return NULL;//check the path correctness
ifstream fin;//1opening the file 2check if the file opening is successful 3put the g in the correct place with seekg
fin.open(path.c_str());
if(a < 0) a=0;
if(b < 0) b=0;
if(a >file_size)
a = b = file_size;
if(b > file_size){
b = file_size;
}
fin.seekg(a , fin.beg);
if(!fin){
cout << "ERROR:File Does Not Exist!" << endl;
return NULL;
}
//opening the output file for
//The search phase
int counter=0 , charNum =a;//this counter hold the number of appearance of the phrase in the file
while(!fin.eof() && charNum < b){
int cnt = 0;char inp;
do{
fin.get(inp);charNum++;
if(phrase[cnt] == inp)
cnt++;
else
break;
}while( cnt<phrase.length() && !fin.eof());
if( cnt == phrase.length()){
counter++;
vec.push_back( ((int)fin.tellg())-1 );
}
}
fin.close();
}
我将运行此程序调用{{1}}并有时收到错误,并且不会一直发生。
答案 0 :(得分:1)
我只是在猜测这里的问题,但你将一个(指向一个)结构传递给所有线程,并且所有线程都有一些共同的指针,它们都在结构中共享,例如typedef void(__closure *callBackMethodMember)(string);
typedef void (*callBackMethodGlobal)(string);
/* And then on 2 overloaded functions */
void addFunction(string funName, callBackMethodMember methodName) {}
void addFunction(string funName, callBackMethodGlobal methodName) {}
。如果有多个线程尝试同时修改向量,则会有race condition。
竞争条件很糟糕,您需要使用某种 lock 来防范它们,例如使用a mutex。