저는 멀티 쓰레딩을 처음 접했고 멀티 쓰레딩을 사용하여 동일한 현재 계정에서 뱅킹 트랜잭션을 시뮬레이션하려고합니다. 각 스레드는 파일에서 수행 할 작업을 읽습니다. 파일에는 정수로 구성된 각 행에 대한 조작이 들어 있습니다. 주 프로그램은 경로에 파일만큼의 스레드를 만들어야합니다.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을"기능에서