SetConsoleCursorPosition和pthread的问题

时间:2016-11-17 08:20:29

标签: c++ multithreading

我试图通过使用线程制作一个简单的“类似乒乓”的迷你游戏来弄清楚如何使用多线程。

这是项目的标题:

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

正如您所看到的,我的显示器无法正常工作。我知道它可能是互斥体,但我不知道我做错了什么 在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

SetConsoleCursorPosition(Thr->P_Hwnd,Thr->P_PosB);Balle之前调整后,您忘记了cout << 'o';