|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
概述:在做贪吃蛇的过程中要用到多线程刷新,但是中间遇到了控制台输出错误的问题。为了简化分析我就将它简化为多线程获取键盘输入,主线程在指定位置输出一个字符。
问题:按下按键时控制台不会更新我按下的按键,长按按键时,才会作出正确的回应。函数加锁,原子变量,主函数加延时,这几种方法都已经用过了,但是没有办法解决,先来寻求帮助。多线程是使用tinythread实现。源码如下
- #include <conio.h>
- #include <windows.h>
- #include "tinycthread.h"
- volatile int run_flag = 0;
- int GetInput(int *cInt);
- int main(void){
- volatile int c_res;
- thrd_t test;
- run_flag = 1;
- thrd_create(&test,GetInput,&c_res); //创建线程
- while (run_flag){
- if (c_res == 'q'){ //如果从线程中受到的q,则退出
- run_flag = 0;
- }else{
- SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),(COORD){.Y=2,.X=2});//WinAPI设置光标位置
- putch(c_res);
- }
- }
- thrd_detach(test);//detach
- return 0;
- }
- int GetInput(int *cInt){
- while (run_flag){
- *cInt = getch(); //从键盘获取输入
- }
复制代码
调试了一下,发现是 putch 函数的问题,第一次可以执行,第二次就卡住不动了
换成 printf 就可以了
- #include <conio.h>
- #include <windows.h>
- #include "tinycthread.h"
- volatile int run_flag = 0;
- int GetInput(int *cInt);
- int main(void){
- volatile int c_res;
- thrd_t test;
- run_flag = 1;
- thrd_create(&test,GetInput,&c_res); //′′½¨Ïß3ì
- while (run_flag){
- if (c_res == 'q'){ //èç1û′óÏß3ìÖDêüμ½μÄq£¬ÔòíË3ö
- run_flag = 0;
- }else{
- SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),(COORD){.Y=2,.X=2});//WinAPIéèÖÃ1a±êλÖÃ
- //putch(c_res);
- printf("%c", c_res);
- }
- }
- thrd_detach(test);//detach
- return 0;
- }
- int GetInput(int *cInt){
- while (run_flag){
- *cInt = getch(); //′ó¼üÅì»ñè¡êäèë
- }
- }
复制代码
|
|