重新启动后,线程无法在 while 循环中再次运行
Thread cannot run again in while loop after restart
我这里有一个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 调用替换为重新创建线程的代码即可。
相关文章:
- 花括号使循环运行一次?
- 如何在这里循环运行?
- 作为无限循环运行
- 插入无限循环运行的单向链表
- 运行功能并保持循环运行C
- OPENCV C .在for循环中在不同的图像像素上绘制一个圆圈(应在每个循环运行时将图像打开)
- 在C 插入内部的手动循环运行不正确
- Windows 生物识别服务在调用 WinBioCaptureSample 时循环运行 SensorAdapterSta
- 为什么我的 do 循环运行多次并且不要求输入?
- 我希望循环运行直到数字为:123
- 如何在按键按下C 循环运行,但将其打破每个升降机
- 如何使用调整后的字符串索引第二次通过循环运行字符串
- 循环运行时错误
- 为什么这个循环运行不可见的代码?工作不正常
- 无法通过循环运行我的代码,但是手动复制和粘贴有效
- 程序以循环运行
- while 循环运行,无论输入是否正确
- C++ - 使用 cin 循环运行 while 后,程序不会再次接受输入
- 不停止While循环运行而未获得预期结果
- 如何向编译器提供有关循环运行最长时间的提示