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

标签 c++ multithreading while-loop handle

我在这里有一个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/

相关文章:

c++ - 如何在 Qt 应用程序中的 pressAndHold 事件期间移动 map ?

c++ - windows下驱动程序编程入门方法

java - 并行和顺序的事件处理

java - while 循环中的 try-catch 方法?

java while循环计数错误

c++ - 在编译一个简单的 Ceres Solver 演示时,是什么让 clang 而不是 g++ 绊倒了?

c++ - 如何使用 RSA/AES 加密/解密较大的文件

.net - 在控制台应用程序中使用 .NET BackgroundWorker 类

linux - 找出由短时间运行的程序创建的线程数

java - While 循环在检查输入之前结束