重新启动后,线程无法在 while 循环中再次运行

Thread cannot run again in while loop after restart

本文关键字:循环 运行 while 线程 重新启动      更新时间:2023-10-16

我这里有一个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 gamen";
while (true) {
inp = _getch();
if (run == 1) 
ResumeThread(handle_t1);
else{   //run == 0
if (inp == 'r') {
system("cls");
cout << "The we_are_even gamen";
run = 1; //restart game
}
else {  //if inp != 'r', exit the game
ExitGame(handle_t1);
t1.join();
return 0;
}
}
}
}

问题是,在我赢得游戏并按"r"重新启动后,线程不会再次运行 虽然应该恢复。我在这里哪里犯了错误?我该如何解决它?我试图在 run = 0 时暂停它并再次恢复,但无济于事。

当您将 r 设置为零时,while 循环将停止,线程函数(在您的情况下为the_game(将退出,这意味着线程将停止。也就是说,当玩家获胜时,您的代码会停止线程而不是挂起它。而且您将无法通过在其上调用 ResumeThread 来恢复线程。

可以等待条件变量,也可以等待WinAPI,也可以等待事件对象。当玩家获胜时,您可以通过让它等待通知/设置此类对象来停止循环。

再三考虑,最简单的方法是在用户按 R 时简单地重新创建线程。只需将 ResumeThread 调用替换为重新创建线程的代码即可。