gpt4 book ai didi

c - 在C中使用信号量

转载 作者:行者123 更新时间:2023-11-30 15:27:05 24 4
gpt4 key购买 nike

我正在学习如何在 C (linux) 中使用信号量。

我想问你:

如何判断订单是立即执行,还是等待?

Example我去 sleep 的理发师:

在函数中:

    void *customer(void *number) {
int num = *(int *)number;

// Leave for the shop and take some random amount of
// time to arrive.
printf("Customer %d leaving for barber shop.\n", num);
randwait(5);
printf("Customer %d arrived at barber shop.\n", num);

// Wait for space to open up in the waiting room...
sem_wait(&waitingRoom);
printf("Customer %d entering waiting room.\n", num);

// Wait for the barber chair to become free.
sem_wait(&barberChair);

// The chair is free so give up your spot in the
// waiting room.
sem_post(&waitingRoom);

// Wake up the barber...
printf("Customer %d waking the barber.\n", num);
sem_post(&barberPillow);

// Wait for the barber to finish cutting your hair.
sem_wait(&seatBelt);

// Give up the chair.
sem_post(&barberChair);
printf("Customer %d leaving barber shop.\n", num);
}

在线sem_wait(&waitingRoom);是否可以检查等待 - true false?

我的意思是:

int time = sem_wait(&waitingRoom);
if(time != 0)
printf("YOU MUST WAIT!");

或者

   int i = isSemaphoreFree()...

我希望你能理解我,抱歉我的英语:-)

最佳答案

看看sem_trywait() sem_... docs

如果信号量当前被阻止,这将立即返回并显示错误。

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

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