gpt4 book ai didi

c - sleep 的理发师陷入僵局

转载 作者:太空宇宙 更新时间:2023-11-04 04:53:33 25 4
gpt4 key购买 nike

我写了 sleep 理发师问题的代码,它看起来很奇怪......代码如下..

#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>

#define MAX_C 10
int a[MAX_C], head=0, tail=0, tmp, tb, tc, count=1;
pthread_mutex_t B;
double time_slot[]={0.125,0.5,0.75,1.00,1.25,1.50,1.75,2.00};

void wait(int a)
{
clock_t g=clock();
while(((float)(clock()-g))/CLOCKS_PER_SEC != time_slot[a]);
}

void barber()
{
printf("barber started\n");
while(1) {
tmp=0;
while(head==tail) {
printf("b\n");
}
tb=rand()%8;
printf("tail:%d\n", tail);
tail=(tail+1)%MAX_C;
wait(tb);
}
}

void customer()
{
printf("customers started\n");
while(1) {
wait(rand()%8);
while((head+1)%MAX_C == tail) {
printf("c\n");
}
a[head]=count-1;
printf("head:%d\n", head);
head=(head+1)%MAX_C;
}
}

int main(int argc, char* argv[])
{
pthread_t b,c;

pthread_mutex_init(&B, NULL);
pthread_create(&c, NULL, (void*)&customer, NULL);
pthread_create(&b, NULL, (void*)&barber, NULL);

pthread_join(b, NULL);
pthread_join(c, NULL);
exit(0);
}

问题是当缓冲区已满时......理发师正在等待客户......但客户根本没有执行!(它既没有等待也没有填充缓冲区)......因为客户while 循环没有执行...

最佳答案

正如 Daneil Fischer 所说...while(((float)(clock()-g))/CLOCKS_PER_SEC != time_slot[a]); 有误我应该用

替换它

while(((float)(clock()-g))/CLOCKS_PER_SEC <= time_slot[a]);

但是,时钟值的这种“丢失”仅在整个缓冲区被填满之后才发生,这仍然很奇怪....

关于c - sleep 的理发师陷入僵局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12159665/

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