C语言 同步问题的伪代码(纸牌游戏)



这与学术有关。

我不熟悉基于同步的编程,并且在为如下所示的程序创建别名时遇到问题:

有一名导演和N名球员。这导演(独立线程(洗牌(洗牌(((,邀请玩家 (邀请玩家(((,然后(分发卡片(((。导演给 控制权交给第一个玩家,他暂停自己,直到游戏结束。一旦导演 收到游戏结束的通知,他检查记录(检查游戏(((以验证卡是否 按照规则玩。

每个玩家都作为单独的线程运行。在可能的初始化之后,玩家会等到她 示意打牌。然后她打一张牌(扑克牌(((。如果当前活跃的玩家检测到游戏已结束(game(( 结束产生 true(,则 通知导演游戏结束并退出。如果游戏尚未结束,玩家会发出信号 下一个玩家并暂停自己,直到再次轮到她。

这是我想到的(记住消费者生产者问题(。请给出您的反馈和建议:

void Director()
{
shuffle_cards();
invite_players();
distribute_cards();
up(&full);
down(&empty);
check_game();
}
void Player()
{
down(&full);
down(&mutex);
play_card();
if (end_of_game == true){
up(&empty);
}
}
  1. 只有一个信号量"full"不会完成唤醒下一个玩家的工作。 每个玩家必须有N 个 sempahores 来完成这项工作。

  2. 导演必须有一个信号量。

  3. 我假设 invite_players(( 中的导演; 函数创建 N 个线程供 N 个玩家玩。

森帕霍尔导演 = 0;

信号量播放器[N] = {0,0, ....0};

void Director()
{
while (true) {
shuffle_cards();
invite_players();   // create the N player threads.
distribute_cards(); // Distribute the cards to players.
// Set all players semaphore in lock mode.
Players[N] = {0,0, ....0};
// Wakeup first player to start the game.
up(&Players[0]);
// Wait till the game is over
down(&Director);
check_game();
}
}
void Player(int i) {
// i is the player number playing the game in this thread.
// Pick up the distributed cards.
pickupCards();
// Start the game.
while (true) {
// Wait for your turn.
down(&Players[i]);
// Check for end game condition.
if (end_of_game == true){
// Leave the game.
break;
}
// Play the game.
play_card();
// Wake up next player.
up(&Players[(i+1)%N]);
}
// You detected the game is over.
// Now try to pass on that information to next neighbor. 
// If next player is still playing, she will quit and pass on the same information.
// If next player is not playing, the end of game is broadcasted to all.
up(&Players[(i+1)%N]);
}

最新更新