gpt4 book ai didi

c - C 中使用 pthread 和信号量的读写器问题

转载 作者:行者123 更新时间:2023-11-30 16:13:17 25 4
gpt4 key购买 nike

我正在尝试通过 C 代码创建读者-作者场景,但我坚持尝试在中间中断读者代码,以便读者不只是进入和退出,它会留下来,更多的读者可以添加。

我现在的程序不会进入多个读者,只要一个进入,它就会离开,然后作家就会来。

我尝试过使用 sleep() 但包含 unistd 库确实会破坏一半的错误代码

#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
sem_t x,y;
pthread_t tid;
pthread_t writerthreads[100],readerthreads[100];
int readercount;

void *reader(void* param)
{
sem_wait(&x);
readercount++;
if(readercount==1)
sem_wait(&y);
sem_post(&x);
printf("\n%d reader is inside",readercount);
sem_wait(&x);
readercount--;
if(readercount==0)
{
sem_post(&y);
}
sem_post(&x);
printf("\n%d Reader is leaving",readercount+1);
}

void *writer(void* param)
{
printf("\nWriter is trying to enter");
sem_wait(&y);
printf("\nWriter has entered");
sem_post(&y);
printf("\nWriter is leaving");
}

int main()
{
int n2,i;
printf("Enter the number of readers:");
scanf("%d",&n2);
int n1[n2];
sem_init(&x,0,1);
sem_init(&y,0,1);
for(i=0;i<n2;i++)
{
pthread_create(&writerthreads[i],NULL,reader,NULL);
pthread_create(&readerthreads[i],NULL,writer,NULL);
}
for(i=0;i<n2;i++)
{
pthread_join(writerthreads[i],NULL);
pthread_join(readerthreads[i],NULL);
}

}

输出的形式为

reader is inside
reader is leaving
reader is inside
reader is leaving
writer is trying to enter
writer has entered
writer is leaving

依此类推,我希望程序中一次有多个读者。

最佳答案

你的代码工作正常。只需给阅读器添加一点延迟,就可以让其他阅读器有时间进入。否则,阅读器完成得太快,并且很少会看到重叠的阅读器。您还忘记将 readercount 初始化为零。

#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
sem_t x,y;
pthread_t tid;
pthread_t writerthreads[100],readerthreads[100];
int readercount = 0;

void *reader(void* param)
{
sem_wait(&x);
readercount++;
if(readercount==1)
sem_wait(&y);
sem_post(&x);
printf("%d reader is inside\n",readercount);
usleep(3);
sem_wait(&x);
readercount--;
if(readercount==0)
{
sem_post(&y);
}
sem_post(&x);
printf("%d Reader is leaving\n",readercount+1);
return NULL;
}

void *writer(void* param)
{
printf("Writer is trying to enter\n");
sem_wait(&y);
printf("Writer has entered\n");
sem_post(&y);
printf("Writer is leaving\n");
return NULL;
}

int main()
{
int n2,i;
printf("Enter the number of readers:");
scanf("%d",&n2);
printf("\n");
int n1[n2];
sem_init(&x,0,1);
sem_init(&y,0,1);
for(i=0;i<n2;i++)
{
pthread_create(&writerthreads[i],NULL,reader,NULL);
pthread_create(&readerthreads[i],NULL,writer,NULL);
}
for(i=0;i<n2;i++)
{
pthread_join(writerthreads[i],NULL);
pthread_join(readerthreads[i],NULL);
}

}

1 reader is inside
Writer is trying to enter
2 reader is inside
2 Reader is leaving
2 reader is inside
Writer is trying to enter
2 Reader is leaving
1 Reader is leaving

关于c - C 中使用 pthread 和信号量的读写器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com