问题遇到的现象和发生背景
通过移动光标的方式,用两个线程执行两个不同函数分别在某列输出不同的数字。由于线程并发,输出的结果不对
问题相关代码,请勿粘贴截图
#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