【发布时间】:2015-05-14 05:30:56
【问题描述】:
我正在为基于IOCP的在线游戏编写服务器,处理游戏消息的核心代码如下:
CMessage ret;
int now_roomnum = recv_msg->para1;
int now_playernum = recv_msg->para2;
/*if(true)
{
cout<<"Received Game Message: "<<endl;
cout<<"type2 = "<<recv_msg->type2;
cout<<" player_num = "<<now_playernum<<" msg= "<<recv_msg->msg<<endl;
cout<<endl;
}*/
if(recv_msg->type2 == MSG_GAME_OPERATION)
{
ret.type1 = MSG_GAME;
ret.type2 = MSG_GAME_OPERATION;
while(game_host[now_roomnum].Ready(now_playernum) == true)
{
;
}
//cout<<"Entered from "<<now_playernum<<endl;
game_host[now_roomnum].SetMessage(now_playernum, recv_msg->msg);
game_host[now_roomnum].SetReady(now_playernum, true);
game_host[now_roomnum].SetUsed(now_playernum, false);
while(true)
{
bool tmp = game_host[now_roomnum].AllReady();
if(tmp == true)
break;
}
//cout<<"AllReady from"<<now_playernum<<endl;
string all_msg = game_host[now_roomnum].GetAllMessage();
game_host[now_roomnum].SetUsed(now_playernum, true);
while(!game_host[now_roomnum].AllUsed())
{
;
}
//cout<<"AllUsed from "<<now_playernum<<endl;
EnterCriticalSection(&cs);
game_host[now_roomnum].ClearReady();
LeaveCriticalSection(&cs);
strcpy_s(ret.msg, all_msg.c_str());
//cout<<"Return msg "<<now_playernum<<": "<<ret.msg<<endl;
}
return ret;
现在,问题是:在 PC 上,当所有cout 都像上面那样评论时,游戏会立即冻结;但是当我取消 cmets 时,服务器运行良好。
更重要的是,当我在笔记本电脑上运行服务器时,一切正常,无论我是否评论cout。我的笔记本电脑和 PC 的主要区别在于我的笔记本电脑的操作系统是 Windows 8.1,而 PC 是 Windows 7。
我完全糊涂了。如果有人能告诉我该怎么做,那将有很大帮助。谢谢!
【问题讨论】:
-
通常当你看到这样一个奇怪的问题时,当你修改不相关的代码时代码似乎停止工作,这可能是你的线程或计时问题,如果你单步执行你的代码会有所帮助一个调试器来找出它在哪里冻结。此外,那些
while(/*true*/);循环可能应该替换为while(/*true*/) Sleep(1);或类似的东西,让操作系统有机会处理其他线程。 -
@Wernsey Sleep(1) 几乎可以肯定是非常糟糕的建议
-
@DavidHeffernan 可能是这样,但您能否详细说明您将如何将当前线程交给操作系统?
-
@Wernsey 这是一个游戏循环。你可能不想屈服。有 SwitchToThread 和许多其他的屈服选项。
-
@DavidHeffernan 我现在已经喝过咖啡,看到了我的方式的错误。
标签: c++ windows iocp online-game