SetConsoleCursorPosition和pthread的问题
Problems with SetConsoleCursorPosition and pthread
我想弄清楚如何通过使用线程制作一个简单的"乒乓"小游戏来处理多线程。
项目标题:
typedef struct
{
HANDLE P_Hwnd;
COORD P_Pos;
COORD P_PosB;
COORD P_Affich;
short P_Cont;
short P_Coups;
pthread_mutex_t P_Sync;
} Params;
void* Raquette(void *);
void* Balle(void *);
这是cpp文件:
using namespace std;
int main(int argc, char* argv[])
{
HANDLE Hwnd;
COORD Pos= {25,20};
COORD PosB= {0,0};
COORD Affich={0,0};
Hwnd = GetStdHandle(STD_OUTPUT_HANDLE);
Params ThrParam = {Hwnd,Pos,PosB,Affich,1,0, PTHREAD_MUTEX_INITIALIZER };
cout<<" ";
for(short i = 0;i < 50;i++)
{
cout<<"_";
}
for(short j = 0;j < 20;j++)
{
cout<<endl<<"|";
for(short i = 0;i < 50;i++)
{
cout<<" ";
}
cout<<"|";
}
pthread_t tball;
pthread_t traquette;
pthread_create(&tball,NULL,Balle,&ThrParam);
pthread_create(&traquette,NULL,Raquette,&ThrParam);
pthread_join(tball,NULL);
pthread_join(traquette,NULL);
return 0;
}
void * Raquette(void* T)
{
short hsp;
hsp = 0;
Params* Thr = (Params*)T;
Thr->P_Pos.Y = 20;
while(Thr->P_Cont != 0)
{
_kbhit();
char wai = _getch();
if(wai == 'k' && Thr->P_Pos.X > 0)
{
hsp = -1;
}
if(wai == 'm' && Thr->P_Pos.X < 45)
{
hsp = 1;
}
pthread_mutex_lock(&(Thr->P_Sync));
SetConsoleCursorPosition(Thr->P_Hwnd , Thr->P_Pos);
cout<<" ";
Thr->P_Pos.X += hsp;
SetConsoleCursorPosition(Thr->P_Hwnd , Thr->P_Pos);
cout<<"=====";
pthread_mutex_unlock(&(Thr->P_Sync));
}
return((void*)0);
}
void * Balle(void* T)
{
Params* Thr = (Params*)T;
short hsp = 1;
short vsp = 1;
while(Thr->P_Cont != 0)
{
if(Thr->P_PosB.X + hsp == 0 || Thr->P_PosB.X + hsp == 50)
{
hsp = -hsp;
}
if(Thr->P_PosB.Y + vsp == 0)
{
vsp = -vsp;
}
if(Thr->P_PosB.Y + vsp == 20)
{
if((Thr->P_PosB.X) + hsp >= (Thr->P_Pos.X-1) && (Thr->P_PosB.X) + hsp <= (Thr->P_Pos.X) + 5)
{
vsp = -vsp;
hsp = (rand()%3) - 1;
}
else
{
Thr->P_Cont = 0;
}
}
pthread_mutex_lock(&(Thr->P_Sync));
SetConsoleCursorPosition(Thr->P_Hwnd,Thr->P_PosB);
cout<<" ";
pthread_mutex_unlock(&(Thr->P_Sync));
Sleep(150);
pthread_mutex_lock(&(Thr->P_Sync));
Thr->P_PosB.X += hsp;
Thr->P_PosB.Y += vsp;
cout<<"o";
pthread_mutex_unlock(&(Thr->P_Sync));
}
return((void*)0);
}
这里是问题的演示。demo
正如你所看到的,我的显示器没有按预期工作。我知道这可能是互斥,但我不知道我做错了什么。
提前感谢您的帮助
您在Balle
中调整后,cout << 'o';
之前忘记了SetConsoleCursorPosition(Thr->P_Hwnd,Thr->P_PosB);
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- 在使用 pthread 和信号量实现生产者-消费者问题时需要帮助
- SetConsoleCursorPosition和pthread的问题
- 使用pthread与CUDA -设计问题
- 从 pthread调用的 OpenMP 代码的性能问题
- 关于pthread调度程序和优先级的问题