2014-12-03 78 views
0

我刚开始学习如何混淆线程和C中的同步编程。我试图编写一个使用线程(POSIX接口)从共享缓冲区中读取选定文件的阅读器。子线程将从缓冲区中检索文件名,而父线程将不定期地从stdin读取文件名并将它们放入缓冲区。我究竟做错了什么?共享缓冲区和同步编程的问题

pthread_mutex_t lock; 

static char* files[NFILES]; 
int top = NFILES-1; 

void putInBuffer(char* file){ 
    pthread_mutex_lock(&lock); 
    if(top < NFILES-1){ 
     files[top] = file; 
     top++; 
    } 
    pthread_mutex_unlock(&lock); 
} 

char* removeFromBuffer(){ 
    char* file; 
    pthread_mutex_lock(&lock); 
    file = files[top]; 
    top--; 
    pthread_mutex_unlock(&lock); 
    return file; 
} 

void* leitor(){ 
    int op,i,r,cl; 
    char* file; 
    char buff[NCHARS]; 
    char teste[NCHARS]; 
    while(1){ 
     pthread_mutex_lock(&lock); 
     file = removeFromBuffer(); 
     printf("%s\n", file); 
     op = open(file, O_RDONLY); 
     if(op == -1) { 
      perror("Open unsuccessful"); 
      pthread_exit((void*)-1); 
     } 
     r = read(op, teste, NBYTES); 
     if(r == -1){ 
      perror("Read unsuccessful"); 
      pthread_exit((void*)-1); 
     } 
     for(i=0; i<NLINES-1; i++){ 
     r = read(op, buff, NBYTES); 
     if(r == -1){ 
      perror("Read unsuccessful"); 
      pthread_exit((void*)-1); 
     } 
     if(strcmp(buff,teste) != 0){ 
      perror("Incorrect file"); 
      pthread_exit((void*)-1); 
     } 
     } 
     cl = close (op); 
     if(cl == -1){ 
      perror("Close unsuccessful"); 
      pthread_exit((void*)-1); 
     } 
     printf("Correct file: %s\n", file); 
     pthread_mutex_unlock(&lock); 
    } 
    pthread_exit((void*)0); 
    return NULL; 
} 

int main(){ 

    pthread_t threads[NTHREADS]; 
    int i,*status; 
    char file[LENFILENAME]; 
    if (pthread_mutex_init(&lock, NULL)) 
    { 
     perror("\n mutex init failed\n"); 
     exit(-1); 
    } 
    for(i=0;i<NTHREADS;i++){ 
     if(pthread_create(&(threads[i]),NULL, leitor,NULL)){ 
      perror("Failed to create thread"); 
      exit(-1); 
     } 
    } 

    while(1){ 
     read(STDIN_FILENO, file, LENFILENAME); 
     printf("%s\n", file); 
     putInBuffer(file); 
     printf("%s\n", removeFromBuffer()); 
    } 
    for (i=0;i<NTHREADS;i++){ 
     if(pthread_join(threads[i],(void**)&status)){ 
      perror("Failed to join thread"); 
      exit(-1); 
     } 
     printf("Thread returned %d\n", status); 
    } 
    pthread_mutex_destroy(&lock); 
    return 0; 
} 

回答

0

鉴于你的程序在做什么,似乎你应该使用单独的信号通知新的输入的子线程,而不是使用您已经创建互斥。

每个子线程都应该在while循环顶部的信号灯上等待,您当前有pthread_mutex_lock()。父母完成putInBuffer后,应释放一次信号量。当一个子线程抓取信号量时,它可以调用removeFromBuffer来获取下一个文件并读取它(即你已经写入的内容)。在孩子完成文件后,它不应该释放信号量,只需回到循环顶部并再次等待。

您已正确使用putInBufferremoveFromBuffer中的互斥锁来保护对共享变量filestop的访问。

+0

感谢您的帮助:) – 2014-12-03 20:40:30