【发布时间】:2020-09-17 17:18:25
【问题描述】:
我正在用 C 实现读写器问题。如您所见,我分叉了 2 次,每次都会生成一个需要等待一段时间的读取器或写入器。我还使用两个信号量满足了线程安全性。首先是保护rcount的mutex,其次是保护互斥的writeblock。问题是我的计数器值没有改变,尽管我将它用作共享内存。
代码:
#include <stdio.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <sys/shm.h>
sem_t mutex,writeblock;
int data = 0,rcount = 0,shmid;
void reader()
{
sem_wait(&mutex);
rcount = rcount + 1;
if(rcount==1)
sem_wait(&writeblock);
int *counter=shmat(shmid,NULL,0);
printf("im a reader and counter is %d \n\n",*counter);
shmdt(counter);
sem_post(&mutex);
sleep(1);
sem_wait(&mutex);
rcount = rcount - 1;
if(rcount==0)
sem_post(&writeblock);
sem_post(&mutex);
}
void writer()
{
sem_wait(&writeblock);
int status=0;
int *counter=shmat(shmid,NULL,0);
*counter++;
printf("im a writer and I incremented the counter and after that the counter is %d \n\n",*counter);
shmdt(counter);
sleep(1);
sem_post(&writeblock);
}
int main()
{
int i,b;
sem_init(&mutex,0,1);
sem_init(&writeblock,0,1);
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
if (shmid <0)
printf("shmget err");
if(fork()==0)
{
for (i=0;i<2;i++)
{
if(fork()==0)
{
sleep(i);
writer();
}
}
}
else
{
for (i=0;i<2;i++)
{
if(fork()==0)
{
sleep(i*2);
reader();
}
}
}
}
错误终端:
$ im a reader and counter is 0
im a writer and I incremented the counter and after that the counter is 0
im a writer and I incremented the counter and after that the counter is 0
im a reader and counter is 0
im a writer and I incremented the counter and after that the counter is 0
im a reader and counter is 0
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
标签: c posix shared-memory