【问题标题】:Use semaphore in C在 C 中使用信号量
【发布时间】:2014-11-29 10:40:30
【问题描述】:

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

我想问你:

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

Example我去睡觉理发师:

在函数中:

    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);是否可以检查等待-真假?

我的意思是:

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

   int i = isSemaphoreFree()...

我希望你能理解我,对不起我的英语:-)

【问题讨论】:

    标签: c semaphore


    【解决方案1】:

    看看sem_trywait()sem_... docs

    如果信号量当前被阻塞,这将立即返回错误。

    【讨论】:

    • then..有可能使睡眠循环:while(sem_trywait()==-1)sleep(5); ?
    • @tilefrae,检查 ifperror 中的 -1 以查看错误。
    • @Chief 两支铅笔对不起,我不明白你的意思,:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    相关资源
    最近更新 更多