gpt4 book ai didi

c++ - 如何在不使用信号量的情况下解决寿司吧问题?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:03:32 26 4
gpt4 key购买 nike

问题:

此代码用于同步问题,称为寿司吧问题。规则如下:

Imagine a sushi bar with 5 seats. If you arrive while there is an empty seat, you can immediately sit. But, if you arrive when all seats are full, it means that all of them are dining together, and you will have to wait for the entire party to leave before you sit down.

脚本:

此处的代码使用信号量在 C 中运行。我一直试图在没有信号量的情况下编写它,但无济于事。它不一定是 C 语言,它可以是 C++ 或其他语言。

我在考虑条件变量,但不确定如何实现它们。如果有人可以提供帮助,我将不胜感激!

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdbool.h>

int eating = 0, waiting = 0;
bool must_wait = false;
sem_t block;
sem_t mutex;

void * sushiBar(void * threadID)
{
usleep(rand() % 1000);

sem_wait(&mutex);
if(must_wait){
printf("Waits: %d seats are available. %d other people waiting.\n", 5-eating, waiting);
waiting++;
sem_post(&mutex);
sem_wait(&block);
waiting--;
}
if(eating == 4)
printf("Last seat is taken.\n");
else{
printf("%d seats available. Sits and eats sushi.\n", 5-eating);
}

eating++;
must_wait = (eating == 5);

if(waiting && (!must_wait))
sem_post(&block);
else
sem_post(&mutex);

usleep((rand() % 901) + 100);
sem_wait(&mutex);
eating--;
printf("Customer leaves: %d seats are available.\n", 5-eating);
if (eating == 0)
must_wait = false;
if ( waiting && (!must_wait))
sem_post(&block);
else
sem_post(&mutex);
return 0;
}

int main(){
int n=10,i=0,retVal=0;
pthread_t *thread;

sem_init(&mutex, 0, 1);
sem_init(&block, 0, 0);

thread = (pthread_t *) malloc (n*sizeof(pthread_t));

for (i=0; i<n; i++){
retVal = pthread_create(&thread[i], NULL, sushiBar, (void*)&i);
if (retVal != 0){
exit(EXIT_FAILURE);
}
}

for(i=0; i<n; i++){
retVal = pthread_join(thread[i],NULL);
if(retVal != 0){
exit(EXIT_FAILURE);
}
}

return 0;
}

最佳答案

我已经在 C++ 中使用 condition_variable 实现了这个问题(基本实现)。您可以将其用作起点并尝试开发您的应用程序

#include <iostream>           
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int noofseats = 0;
bool ready = false;

void enter_bar(int id) {
std::unique_lock<std::mutex> lck(mtx);

while (noofseats >= 5)
{
//lock threads if seats are filled
cv.wait(lck);
std::cout << "User : " << id << "waiting for seat" << std::endl;

}
std::cout << "User : " << id << "got seat" << std::endl;
noofseats++;

}

void exit_bar()
{
std::unique_lock<std::mutex> lck(mtx);
noofseats--;
if(noofseats < 5)
{
//would unloack other threads if seats are present
cv.notify_all();
}

}

int main()
{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i<10; ++i)
{
threads[i] = std::thread(enter_bar, i);
}

//three people exit bar
exit_bar();
exit_bar();
exit_bar();

for (auto& th : threads) th.join();

return 0;
}

关于c++ - 如何在不使用信号量的情况下解决寿司吧问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056126/

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