线程重启后不能再运行while循环。

问题描述 投票:1回答:1

我这里有一段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时暂停它,然后再恢复,但没有用。

c++ multithreading while-loop handle
1个回答
1
投票

当你把r设为0时,while循环将停止,而线程函数(在你的例子中。the_game)将退出,这意味着该线程将停止。也就是说,当玩家获胜时,你的代码会停止该线程,而不是暂停它。而且你不能通过调用ResumeThread来恢复线程。

你可以等待一个 条件变量 或者如果你使用WinAPI,在一个 事件 对象。当玩家获胜时,你可以让它等待这样一个对象被通知设置,从而停止循环。

仔细想想,最简单的方法是在用户按R键时简单地重新创建线程,只要用重新创建线程的代码代替ResumeThread调用即可。

© www.soinside.com 2019 - 2024. All rights reserved.