1
我有一個文件,其中包含一個文件名列表,其中我想要搜索一個詞並替換它 我修改了一些代碼,僅僅顯示相關部分 問題是如果我有隻有一個文件在該列表中,它不會用多線程處理它,因爲線程只在我有多個文件時才工作 所以我想保留當前的線程配置,但我想在處理部分添加一些線程 我有驗證碼:從pthread運行pthreads
struct words_list {
char word[20];
struct words_list * next;
};
FILE * INFILE;
int num_thread = 10;
// Mutex variables
pthread_mutex_t input_queue;
pthread_mutex_t word_list;
int main(int argc,char **argv)
{
//some code is missing
if((INFILE = fopen(myfile,"r")) == NULL) {
fprintf(stderr,"Can't open input file\n");
exit(0);
}
for(i = 0 ; i < number_thread; i++)
{
if(pthread_create(&thread_id[i],NULL,&search,NULL) != 0)
{
i--;
fprintf(stderr,RED "\nError in creating thread\n" NONE);
}
}
for(i = 0 ; i < number_thread; i++)
if(pthread_join(thread_id[i],NULL) != 0)
{
fprintf(stderr,RED "\nError in joining thread\n" NONE);
}
fflush(INFILE);
fclose(INFILE);
}
void * search(void * data)
{
char file[20];
while (!feof(INFILE))
{
if (fgets(file,sizeof(file),INFILE) != NULL)
{
if (strlen(file) < 8)
break;
if (file[strlen (file) - 1] == '\n')
file[strlen (file) - 1] = '\0';
}
process(file);
}
return NULL;
}
void process(char *filename)
{
char buff[512];
char word[20];
struct words_list * curr_word = first_word;
if(verbose != 0)
fprintf(stderr,"Processing: %s\n",filename);
while(curr_word != NULL)
{
//some code missing
pthread_mutex_lock(&word_list);
strncpy(word,curr_word->word,sizeof(word) - 1);
pthread_mutex_unlock(&word_list);
**//replace_word must run with multiple threads**
ret = replace_word(word,buff,sizeof(buff));
//end of threads part
//code missing
}
}
我怎樣才能在加粗部分添加其他並行線程所以它可以用多個線程處理每個文件?
以什麼方式代碼類似於您在主要使用的代碼失敗? –
我想要類似於我在main中使用的東西,但不知道如何添加它以避免一些混亂。 –
如果文件列表中只包含一個文件,是否要用多個線程處理文件?它不會使用當前的'process'實現。你需要改變它。 :) – Bechir