Implement Threading in C

117 views Asked by At

I'm currently working on a mini game project, and I have a problem with this specific mechanic:

void monsterMove(){
   //monster moves randomly
}

void playerMove(){
   //accepting input as player movement using W, A, S, D
}

However, the project requires the monsters to keep moving at all times, even when the player is not moving.

After some research, I figured out that multithreading is needed to implement this mech since both monsterMove() and playerMove() needs to run concurrently even when playerMove() hasn't received any input from user.

Specifically there are 2 questions I want to address:

  1. Which function needs to be made as a thread?
  2. How to build the thread?

Sadly, I found no resource with specifically this type of question because everything on the Internet just seem to point out how multithreading can work as parallelism in a way, but not in such implementations.

I was thinking that monsterMove() will be run recursively while playerMove() will be made as the thread, since monsterMove() will need to run every n seconds even when playerMove() thread is not finished yet (no input yet). Although I might be wrong for the most part.

Thank you in advanced!

(P.S. Just to avoid misunderstandings, I am specifically asking about how thread and multithreading works, not the logic of the mech.)

Edit: Program is now working! However, any answer/code related to how this program is done with multithreading is immensely appreciated. :)

1

There are 1 answers

3
Jabberwocky On BEST ANSWER

You don't need multithreading for this:

The basic structure is depicted in this pseudocode:

while (1)
{
   check if input is available using kbhit

   if (input available)
     read user input using getch

   move player depending on user input
   move monsters
}

You could use multithreading using the CreatdThread function, but your code will just become overly complex.