#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
(不是 pthread 或信号量)
如果以上是我使用的唯一库,我如何确保读者在从共享缓冲区加载之前等待第一个写入器输入?
当我运行程序时,在我让编写器调用用户输入之前,阅读器会在缓冲区中打印垃圾值。并且scanf
不起作用,它不等待任何用户输入并继续运行。看起来主流程在所有孩子完成之前就结束了,如果发生这种情况,孩子就会停止输入,那么有没有办法解决?
喜欢:
@ubuntu.....(returned?)
reader gets the data:1
Enter your data:
reader gets the data:1
我的源代码如下:
void reader(int i)
{
int data;
if(nextp == N)
nextp=0;
printf("\nEnter the data(writer %d) :",i);
scanf("%d",(buffer+nextp));
nextp++;
}
void writer(int i)
{
int g;
if(nextc == N)
nextc=0;
g=*(buffer+nextc++);
printf("\nreader %d gets the data:%d\n",i,g);
}
in main():
int k;
for(k=RW;k>0;--k)//RW is number of readers and writers
{
pid = fork();
if(!pid)
{
pid = fork();
if(pid>0)//writer (child)
{
for(i=0;i<N;i++)
{
P(empty);
P(mutex); // Entering critical section
P(write);
writer(k);
V(write);
V(mutex); // Exit from critical section
V(full);
}
wait();
}
if(pid==0)//reader (grandchild)
{
int readsize;
readsize = N*RW;
for(i=0;i<readsize;i++)
{
P(full);
P(mutex); // Entering critical section
P(rd_count);
if(N-1 == (j=sem_val(rd_count))) /* Write lock for first reader */
P(write); /* Once we have it, it keeps writers at bay */
V(mutex);
reader(k);
P(mutex);
V(rd_count);
if(N == (j=sem_val(rd_count))) /* When last reader leaves: */
V(write); /* Allow writers */
V(mutex);
V(empty); // Exit from critical section
}
wait();
}
}
}
sem_val
是自定义getval
函数。
P
是自定义-1 semop 函数。
V
是自定义 +1 semop 函数。
如果有逻辑或语法错误,请随时指出。提前致谢!