SetConsoleCursorPosition和pthread的问题

Problems with SetConsoleCursorPosition and pthread

本文关键字:问题 pthread SetConsoleCursorPosition      更新时间:2023-10-16

我想弄清楚如何通过使用线程制作一个简单的"乒乓"小游戏来处理多线程。

项目标题:

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);