主线程中应执行其他程序
时间: 2024-02-24 16:55:58 浏览: 22
如果您希望主线程在按键检测线程运行的同时执行其他程序,可以在主线程中添加适当的代码。例如,您可以在主线程中使用一个无限循环,不断地输出一些信息,并在用户按下 ESC 键时结束循环。修改后的代码如下:
```c++
#include <iostream>
#include <thread>
#include <chrono>
// 检测按键的线程函数
void detect_key_thread()
{
while (true)
{
if (GetAsyncKeyState(VK_ESCAPE))
{
std::cout << "按下了 ESC 键" << std::endl;
break; // 结束按键检测线程
}
else if (GetAsyncKeyState(VK_SPACE))
{
std::cout << "按下了 SPACE 键" << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main()
{
// 创建检测按键的线程
std::thread detect_key(detect_key_thread);
// 主线程执行其他程序
while (true)
{
std::cout << "主线程正在执行其他程序..." << std::endl;
if (GetAsyncKeyState(VK_ESCAPE))
{
std::cout << "按下了 ESC 键,结束程序" << std::endl;
break; // 结束主线程循环
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
// 等待按键检测线程结束
detect_key.join();
return 0;
}
```
在这个示例程序中,我们在主线程中使用一个无限循环不断地输出一些信息,同时检测用户是否按下 ESC 键,如果按下了就结束循环。在`detect_key_thread`函数中,我们也检测用户是否按下了 ESC 键,如果按下了就结束按键检测线程。在主线程循环结束后,我们等待按键检测线程结束,然后退出程序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)