我無法停止KeyListener
函數中的while循環。 Timer
函數每10秒鐘聲明Active
爲false
。但KeyListener
函數中的while
循環仍然在運行。通過使用線程停止while循環C++
我想不通爲什麼循環繼續運行;每個週期它應測試Active
是否爲真,如果不是(因爲在10秒後應該關閉),則循環不應該運行。但它確實如此。
void KeyListener(bool Active)
{
cout << Active << endl; //debug
while (Active==true){
cout << "loop still running." << endl; //debug
Sleep(100);
for (int i=8;i<=190;i++){
if (GetAsyncKeyState(i) == -32767){
KeyWrite(i); // (turns the numbers into characters)
}
}
}
}
void Timer(void* pParams){
while (true){
Sleep(10000);
KeyListener(false); // Active = false
cout << "KeyListener(false)" << endl; // debug
}
}
int main()
{
_beginthread(Timer, 0, NULL);
KeyListener(true);
return 0;
}
我鏈接了代碼,因爲我不知道如何/沒有特權嵌入它。 – Rob 2012-04-26 16:36:21
在運行到線程之前,先了解C++中函數的工作原理。 – Dani 2012-04-26 16:39:05
你正在調用這個函數兩次。你不停止第一個你正在創建另一個立即停止。 – twain249 2012-04-26 16:40:04