1

我是多线程的新手,我正在尝试使用多线程在同一个经常账户上模拟银行交易。每个线程从文件中读取要执行的操作。该文件将包含一个由整数组成的每一行的操作。主程序必须创建与路径中的文件一样多的线程。

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);

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

alberto@ubuntu:~/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 没有使他的工作一样。我真的很感激这方面的一点帮助,因为我真的不知道出了什么问题。

非常感谢。

4

2 回答 2

0

在你的“readfile”函数中

线

char * file_path = (char*)arg;

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

在那里制作一份记忆副本。

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

于 2012-11-17T00:52:56.133 回答
0

首先,我看不到您为 pathaux 分配内存的位置。我想知道 strcpy 或 strcat 是如何工作而不是内存分段的。尝试使用 C++ 编译器进行编译,它可能会抱怨。

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

于 2012-11-17T00:53:59.043 回答