2012-11-17 62 views
1

我是多线程新手,我尝试使用多线程模拟同一个当前帐户上的银行事务。 每个线程都从文件读取要执行的操作。该文件将包含每行由整数组成的操作。主程序必须创建与路径中文件一样多的线程。MULTITHREADING c - 在同一个文件中读取几个文件

int main(int argc,char*argv[]){ 

    DIR *buff; 
struct dirent *dptr = NULL; 
pthread_t hiloaux[MAX_THREADS];  
int i=0,j=0, nthreads=0; 
char *pathaux; 


memset(hiloaux,0,sizeof(pthread_t)*MAX_THREADS); 
diraux=malloc((267+strlen(argv[1]))*sizeof(char)); 
buff=opendir(argv[1]); 
while((dptr = readdir(buff)) != NULL && nthreads<MAX_THREADS)//read files in the path 
    { 


    if (dptr->d_name[0]!='.'){  
     pthread_mutex_lock(&mutex_path);//mutual exclusion 
     strcpy(pathaux,argv[1]);   
     strcat (pathaux,"/"); 
     strcat (pathaux,dptr->d_name);//makes the route (ex:path/a.txt) 

     pthread_create(&hiloaux[nthreads],NULL,readfile,(void *)pathaux); 
     //creates a thread for each file in the path 
        nthreads++; 
    } 

} 

for (j=0;j<nthreads;j++){ 
pthread_join(hiloaux[j],NULL); 
} 

    closedir(buff); 
    return 0; 

} 

我的问题是线程似乎没有收到正确的路径参数。即使我已经放置了一个互斥体(mutex_path),它们都会读取同一个文件。我在函数readfile()中解锁这个互斥锁,。

void *readfile(void *arg){ 
FILE *fichero; 
int x=0,n=0; 
int suma=0; 
int cuenta2=0; 


char * file_path = (char*)arg; 
n=rand() % 5+1; //random number to sleep the program each time I read a file line 
pthread_mutex_unlock(&mutex_path);//unlock the mutex 

fichero = fopen(file_path, "r"); 

    while (fscanf (fichero, "%d", &x)!=EOF){ 

      pthread_mutex_lock(&mutex2);//mutual exclusion to protect variables(x,cuenta,cuenta2)   

     cuenta2+=x;  

      if (cuenta2<0){ 
     printf("count discarded\n"); 
      } 

      else cuenta=cuenta2;  
      pthread_mutex_unlock(&mutex2); 

    printf("sum= %d\n",cuenta); 
    sleep(n); //Each time i read a line,i sleep the thread and let other thread read other fileline 
} 
pthread_exit(NULL); 
fclose(fichero); 

} 当我运行程序我得到这个输出

[email protected]:~/Escritorio/practica3$ ./ejercicio3 path 
read file-> path/fb 
read -> 2 
sum= 2 
read file-> path/fb 
read -> 2 
sum= 2 
read file-> path/fb 
read -> 4 
sum= 6 
read file-> path/fb 
read -> 4 
sum= 6 
read file-> path/fb 
read -> 6 
sum= 12 
read file-> path/fb 
read -> 6 
sum= 12 

它似乎运作良好,它读取一行,在此期间,另一个线程完成其工作休眠一时间,但问题是两个线程都打开相同的文件(路径/ fb)。 正如我之前所说,我认为问题是在路径参数,就像mutex_path没有使他的工作。 我真的很感谢这个帮助,因为我真的不知道什么是错的。

非常感谢。

回答

0

在你 “的ReadFile” 功能

线

字符* FILE_PATH =(字符*)ARG;

只是将指针复制到字符串内存中,而不是内存本身。 因此,当工作线程继续时,它可以(并且仍然)会被人线程改变。

在那里做一个内存拷贝。

或者甚至更好地将主线程中不同内存中的所有参数存储到线程中,因此您根本不需要第一个互斥量。

0

首先,我没有看到在哪里为pathaux分配内存。我想知道strcpy或strcat是如何工作的,而不是内存分割。尝试使用C++编译器编译,它可能会抱怨。

至于你传递指针的问题,所以每个线程指向相同的位置。 正确的方法是在readdir循环中 - 1.创建内存并复制它的路径(注意你想在循环中每次创建内存) 2.将这个内存传递给新线程。 如果你这样做: a。你不必使用互斥量路径。 b。在readfile方法结束时调用free。