2012-11-17 4 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 

잘 작동하는 것 같다이 출력을 얻을 하지만 문제는 두 스레드가 동일한 파일 (path/fb)을 열어야한다는 것입니다. 문제가 경로 인수에 있다고 생각하기 전에 mutex_path가 그의 작업을하지 않았던 것과 같습니다. 무엇이 잘못 되었는가를 알지 못해서 약간의 도움을 주시면 감사하겠습니다.

대단히 감사합니다. 하여 "ReadFile을"기능에서

답변

0

라인

* CHAR FILE_PATH = (숯 *) ARG;

문자열 메모리는 포인터 만 복사하지만 메모리는 복사하지 않습니다. 그래서 작업자 스레드가 계속 진행되는 동안 여전히 맨 스레드에 의해 변경 될 수 있습니다.

거기에 메모리 복사본을 만드십시오.

또는 주 스레드의 다른 메모리에 이미 모든 인수를 스레드에 저장하는 것이 더 좋으므로 첫 번째 뮤텍스가 필요하지 않을 것입니다.

0

첫 번째로 나는 어디에서 pathaux에 대한 메모리를 할당하는지 보지 못합니다. strcpy 또는 strcat가 메모리 분할보다는 어떻게 작동하는지 궁금합니다. C++ 컴파일러로 컴파일을 시도하면 불평 할 수 있습니다.

문제에 관해서는, 모든 스레드가 동일한 위치를 가리 키도록 포인터를 전달하고 있습니다. 올바른 접근 방식은 readdir 루프 내부 일 것입니다 - 1. 메모리를 생성하고 경로를 복사하십시오 (루프에 매회 메모리를 생성하려고합니다). 2.이 메모리를 새 스레드로 전달하십시오. 이렇게하면 : a. 뮤텍스 경로를 사용할 필요가 없습니다. b. readfile 메서드의 끝에서 free를 호출하십시오.

관련 문제