gpt4 book ai didi

c++ - 允许任何进程发送退出消息

转载 作者:行者123 更新时间:2023-11-30 17:46:45 25 4
gpt4 key购买 nike

我在模拟跨所有进程玩游戏的 C/C++ MPI 程序中存在关系问题。如果任何进程获胜,包括 master,该进程应该告诉所有其他进程停止玩游戏,以便将结果发送到 master 并由 master 进行总计。

问题是我有时会在获胜进程之上看到 1 个或多个进程说他们先获胜。这会导致在完成之前长时间挂起(在某些情况下超过一分钟)。我不确定我是否在所有进程之间正确处理退出消息情况。

更新:该程序在单台计算机上运行,​​而不是通过网络运行。该机器未联网。

更新2:由于内部游戏代码导致太多操作,我能够大大减少延迟问题。我仍在寻找对使用 Irecv/Isend 退出进程的方式的解释。

更新3:找到了我的问题,如我的答案所示。

这是我的应用程序中的一些代码,可以提供帮助。

int max_streak_length; // set in main from argv[], greater than 0
bool should_quit = false;

void checkMessages()
{
static int recvFlag
static bool msgBuff;
static MPI_Request request;
MPI_Status status;

// Are we already listening
if( request )
{
// Test for message
MPI_Test(&request, &recvFlag, &status);

if( recvFlag )
{
if( status.MPI_TAG == TAG_QUIT )
should_quit = true;
}
}

// Start listening if we aren't
if( !request )
MPI_Irecv(&msgBuff, 1, MPI_C_BOOL, MPI_ANY_SOURCE, TAG_QUIT, MPI_COMM_WORLD, &request);
}

void processMaster(int numProcs) {
double start = MPI_Wtime();
Game game(max_streak_length);

do
{
if( numProcs > 1 )
checkMessages();
game.play();
} while( !should_quit && !game.is_game_over() );

// Let other processes know they should stop, if I won
if( !should_quit && game.is_game_over() )
{
cout << "Master wins " << MPI_Wtime() << endl;
for( int pID = 1; numProcs > 1 && pID < numProcs; ++pID )
{
MPI_Request r;
MPI_Isend(&should_quit, 1, MPI_C_BOOL, pID, TAG_QUIT, MPI_COMM_WORLD, &r);
}
}

cout << "master quitting" << endl;
}

void processSlave(int numProcs, int rank) {
Game game(max_streak_length);

do
{
checkMessages();
game.play();
} while( !should_quit && !game.is_game_over() );

// Let other processes know they should stop, if I won
if( !should_quit && game.is_game_over() )
{
cout << rank << " wins " << MPI_Wtime() << endl;
for( int pID = 0; pID < numProcs; ++pID )
{
if( pID == rank )
continue;
MPI_Request r;
MPI_Isend(&should_quit, 1, MPI_C_BOOL, pID, TAG_QUIT, MPI_COMM_WORLD, &r);
}
}

cout << rank << " quitting" << endl;
}

最佳答案

我解决了我的问题。我不再遇到延迟,问题出在我的游戏程序逻辑本身。 processSlave for 循环已被修改为具有另一个条件 pID !=rank,这破坏了逻辑,导致在发送 TAG_QUIT 消息时跳过进程。

关于c++ - 允许任何进程发送退出消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19171738/

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