我试图使用openmp来实现读写器问题。当输入器在输入输入之前获取锁定时,一些读者会读取缓冲区。我使用fgets()从stdin获取输入。理想情况下,光标应停在输入输入的位置。任何人都可以向我解释一下这里发生了什么。代码如下
#include<stdio.h>
#include<omp.h>
omp_lock_t r;
omp_lock_t w;
char buffer[10];
int rw=0;
int nr,nw;
void start_read(){
omp_set_lock(&r);
nr++;
if(nr==1){
omp_set_lock(&w);
printf("Reader acquired lock\n");
}
omp_unset_lock(&r);
}
void end_read(){
omp_set_lock(&r);
nr--;
if(nr==0){
omp_unset_lock(&w);
printf("Reader released lock\n");
}
omp_unset_lock(&r);
}
void writer_part(){
omp_set_lock(&w);
printf("\nWriter acquired lock\n");
printf("thread %d writing contents --\n",omp_get_thread_num());
printf("change contents of the buffer\n");
fgets(buffer,10,stdin);
printf("%s",buffer);
omp_unset_lock(&w);
printf("Writer released lock\n");
}
void reader_part(){
start_read();
printf("thread %d Reading contents -- %s",omp_get_thread_num(),buffer);
printf("\n");
end_read();
}
int main(){
int i;
omp_set_num_threads(8);
omp_init_lock(&r);
omp_init_lock(&w);
printf("enter the number of writers\n");
scanf("%d",&nw);
printf("enter number of readers\n");
scanf("%d",&nr);
getchar();
printf("initiliaze the buffer\n");
fgets(buffer,10,stdin);
printf("%s",buffer);
#pragma omp parallel for
for(i=0;i<(nr+nw);i++){
if(i<nw){
writer_part();
}else{
reader_part();
}
}
printf("\n\n");
return 0;
}