lundi 22 août 2016

Threads with same argument objects give different values

I have a problem where two threads with different functions and same argument objects result in giving different values for those objects.

To clearify, please observe the following code:

class Player(){
    // Definition of Player here
    // with get- and set functions
    // for a certain value.
}

class Game(){
    static void Draw(Player p){
        while(1){
            gotoxy(p.getValue(), 15);
            cout << p.name();
       }
    }

    static void Move(Player p){
        int x = p.getValue();
        while(1){
            if(_kbhit()){
                p.setValue(++x);
            }
        }
    }

    void startGame(){
        Player pl1(5);

        thread thd1(Move, pl1);
        thread thd2(Draw, pl1);
        thd1.join();
        thd2.join();
    }  

}

While the value 'x' is changing in the function 'Move' for every key stroke, when getting that value in function 'Draw' still has the initial value for 'pl1' (which is 5).

How can I get 'Draw' to aquire the same value that 'Move' has given? I appreciate any help and guidance.

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire