提问者:小点点

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


我这里有一个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);
}

在main中,我使用线程运行游戏,同时从键盘输入,如下所示

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'重启后,线程没有再次运行,尽管它应该恢复。 我哪里犯错了? 我该怎么修好呢? 我曾尝试在run=0时挂起它,然后再次恢复,但没有效果。


共1个答案

匿名用户

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

您可以在条件变量上等待,如果使用WinAPI,则可以在事件对象上等待。 当玩家获胜时,通过使其等待通知/设置这样的对象来停止循环。

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