Passing Parameters to Function When Multithreading

161 views Asked by At

I have an assignment to create a game like Frogger (you know - the game where a frog has to cross the street). So far I've created the logic behind the movement of the frog and the cars but I can't seem to run the processes simultaneously. I know that multithreading is the correct way to do this, but I'm having some trouble in passing my parameters through _beginthread.

Here's what I have so far:

void moveCarsLeft(int x, int y) {
    if (y < 0) {
        field[x][y + 4] = '_';
        Sleep(600);
        refreshField();
        showField();
        if (y == -4) {
            moveCarsLeft(x, WIDTH-1);
        }
        moveCarsLeft(x, y - 1);
    }
    else {
        if (y > WIDTH-4) {
            field[x][y] = '-';
            Sleep(600);
            refreshField();
            showField();
            moveCarsLeft(x, y - 1);
        }
        else {
            field[x][y + 4] = '_';
            field[x][y] = '-';
            Sleep(600); // this is what's messing up the whole thing
                        // it stops the whole program
                        // and that's why I think I need multithreading
            refreshField();
            showField();
            moveCarsLeft(x, y - 1);
        }
    }
}

void moveCarsRight(int x, int y) {
... // the opposite of moveCarsLeft()
}

...
int main() {
...
    _beginthread(moveCarsLeft, 0, what do I put here?);
...
}

So, I'd be really grateful if someone could tell me the correct way to achieve this functionality. Thanks in advance : ]

2

There are 2 answers

1
Gianluca Ghettini On BEST ANSWER

You don't really need multithreading... a typical old-style game engine would be:

while(1)
{
   userInput = ReadUserInput();
   currentGameStatus = UpdateGameStatus(oldGameStatus, userInput);
   DrawScreen(currentGameStatus);
   oldGameStatus = currentGameStatus;
}

of course this is just pseudo-code to grasp the basic idea...

however if you want to use multithreading you could use a shared game status container which the running threads can access and/or modify (you need to protect the critical sections with some mutexes).

If you use multithreading then expect some minor concurrency issues (e.g. the frog being run over by a car before it actually happens on screen, or the converse) because you lost the perfect state sequentiality given by a single loop in which the game proceeds step-by-step

0
ScottMcP-MVP On

"what do I put here?"

You put a pointer to a struct. You define the struct to contain all of the parameters you want to pass.