L____kk 2022-06-28 16:59 采纳率: 100%
浏览 40
已结题

C语言多线程操作多函数 冲突

问题遇到的现象和发生背景

通过移动光标的方式,用两个线程执行两个不同函数分别在某列输出不同的数字。由于线程并发,输出的结果不对

问题相关代码,请勿粘贴截图
#include <pthread.h>
#include<stdio.h>
#include<windows.h>
void gotoxy(int x, int y){
    COORD pos;
    HANDLE hOutput;
    pos.X = x;
    pos.Y = y;
    hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hOutput, pos);
}
void * fun1(void * a){
    int t=0;
    while(t<20){
        Sleep(200);
        gotoxy(10,t++);
        printf("11");
    }
}
void* fun2(void *a){
    int t=0;
    while(t<20){
        Sleep(200);
        gotoxy(1,t++);
        printf("22");
    }
}
int main(){
    pthread_t pthread1,pthread2;
    pthread_create(&pthread1,NULL,&fun1,NULL);
    pthread_create(&pthread2,NULL,&fun2,NULL);
    
    pthread_join(pthread1,NULL);
    pthread_join(pthread2,NULL);
}

运行结果及报错内容
      2211

22 11
2211
1122
22 11
2211
2211
22 11
22 11
22 11
22 11
22 11
22 11
22 11
22 11
22 11
22 11
22 11
2211
1122

我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

2条回答 默认 最新

  • 关注
    #include <pthread.h>
    #include <stdio.h>
    #include <windows.h>
    
    pthread_mutex_t m;
    
    void gotoxy(short x, short y)
    {
        COORD pos;
        HANDLE hOutput;
        pos.X = x;
        pos.Y = y;
        hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
        pthread_mutex_lock(&m);
        SetConsoleCursorPosition(hOutput, pos);
    }
    
    void *fun1(void *unused)
    {
        short t = 0;
        while (t < 20)
        {
            gotoxy(10, t++);
            printf("11");
            pthread_mutex_unlock(&m);
        }
        pthread_exit(NULL);
        return NULL;
    }
    
    void *fun2(void *unused)
    {
        short t = 0;
        while (t < 20)
        {
            gotoxy(1, t++);
            printf("22");
            pthread_mutex_unlock(&m);
        }
        pthread_exit(NULL);
        return NULL;
    }
    
    int main()
    {
        pthread_mutex_init(&m, NULL);
    
        pthread_t pthread1;
        pthread_t pthread2;
    
        pthread_create(&pthread1, NULL, &fun1, NULL);
        pthread_create(&pthread2, NULL, &fun2, NULL);
    
        pthread_join(pthread1, NULL);
        pthread_join(pthread2, NULL);
    
        pthread_mutex_destroy(&m);
    
        return 0;
    }
    
    
    本回答被专家选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月2日
  • 专家已采纳回答 9月24日
  • 创建了问题 6月28日

悬赏问题

  • ¥15 求:可不可以提供一些 在国内可以用,低代码不要太难 在电脑上可以下载的 制作app的软件
  • ¥60 找人回答kibana8.14.3二次集成开发,自定义插件ui导航栏如何设置
  • ¥15 fluke高精度万用表8845A型号测交流电压一直跳动,且去掉输入后显示不归零
  • ¥15 不同模型怎么用同一个shader
  • ¥15 安卓启动没有ais proxy与v4l2的log打印
  • ¥15 go怎么读取mdb文件里面的数据
  • ¥60 Matlab联合CRUISE仿真编译dll文件报错
  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据