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

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日