我刚刚开始学习如何用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("%sn", 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: %sn", 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 failedn");
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("%sn", file);
putInBuffer(file);
printf("%sn", removeFromBuffer());
}
for (i=0;i<NTHREADS;i++){
if(pthread_join(threads[i],(void**)&status)){
perror("Failed to join thread");
exit(-1);
}
printf("Thread returned %dn", status);
}
pthread_mutex_destroy(&lock);
return 0;
}
鉴于您的程序正在做什么,您似乎应该使用单独的信号量来通知子线程新输入,而不是使用您创建的互斥锁。
每个子线程都应等待while
循环顶部的信号量,您当前pthread_mutex_lock()
。 父级完成putInBuffer
后,应释放一次信号量。 当子线程获取信号量时,它可以调用removeFromBuffer
以获取下一个文件,并读取它(即您已经编写的内容)。 孩子完成文件后,它不应该释放信号量,只是回到循环的顶部并再次等待它。
您已在 putInBuffer
和 removeFromBuffer
中正确使用了互斥锁来保护对共享变量的访问 files
和 top
。