鱼C论坛

 找回密码
 立即注册
查看: 1303|回复: 1

[已解决]C11多线程问题

[复制链接]
发表于 2021-4-2 09:52:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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(); //从键盘获取输入
    }
最佳答案
2021-4-2 13:46:09
调试了一下,发现是 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(); //′ó¼üÅì»ñè¡êäèë
    }
}

tinythread.zip

8.21 KB, 下载次数: 1

tinythread

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-4-2 13:46:09 | 显示全部楼层    本楼为最佳答案   
调试了一下,发现是 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(); //′ó¼üÅì»ñè¡êäèë
    }
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 21:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表