我在这里有一个C++代码,它将制作一个游戏,它将根据键盘输入生成随机数,如果数字为偶数,则得分会增加。如果得分是10,则您赢了,您可以重新开始或退出游戏。
using namespace std;
int score = 0, run = 1;
char inp = 'z';
void the_game() {
int x = 0;
while (run) {
if ('a' <= inp && inp <= 'j') {
srand((unsigned)time(NULL));
x = (rand() % 11) * 2; //if 'a' <= inp <= 'j', x is always even
cout << "Number: " << x << endl;
}
else { // and if not, x is random
srand((unsigned)time(NULL));
x = (rand() % 11);
cout << "Number: " << x << endl;
}
if (x % 2 == 0) {
score++;
cout << "Current Score: " << score << "\n";
}
if (score == 10) {
run = 0;
cout << "You Win! press R to restart and others to exit" ;
}
Sleep(1000);
}
}
void ExitGame(HANDLE t) {
system("cls");
TerminateThread(t, 0);
}
总的来说,我使用线程来运行游戏,同时从键盘输入如下所示
int main() {
thread t1(the_game);
HANDLE handle_t1 = t1.native_handle();
cout << "The we_are_even game\n";
while (true) {
inp = _getch();
if (run == 1)
ResumeThread(handle_t1);
else{ //run == 0
if (inp == 'r') {
system("cls");
cout << "The we_are_even game\n";
run = 1; //restart game
}
else { //if inp != 'r', exit the game
ExitGame(handle_t1);
t1.join();
return 0;
}
}
}
}
问题是,在我赢得游戏并按“r”重新启动后,线程不再运行
尽管应该恢复。我在这里哪里出错了?我该如何解决?我试图在运行= 0时暂停它,然后再次恢复,但无济于事。
最佳答案
当您将r设置为零时,while循环将停止并且线程函数(在您的情况下为the_game
)将退出,这意味着线程将停止。也就是说,当玩家获胜时,您的代码将停止线程而不是将其挂起。而且,您将无法通过在其上调用ResumeThread来恢复该线程。
您可以在condition variable对象上等待Event,也可以使用WinAPI。当玩家获胜时,可以通过使其等待此类对象被通知/设置来停止循环。
再三考虑,最简单的方法就是在用户按下R键时重新创建线程。只需将ResumeThread调用替换为重新创建线程的代码即可。
关于c++ - 重新启动后,线程无法在while循环中再次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62390082/