Hello.
I moved my AI evaluation function to run on a separated thread and now all random number generator calls returns the same number.
On the main thread everything is fine.
My RNG function:
Are you initializing the random numbers with srand?
I was calling srand(time(NULL)) at the beggining of the program. Calling it on the thread function solved the problem.
But... the program crashed on exit.
Do I have to use a mutex to ensure the safety of the srand/rand calls? I'm still kinda new to multithreaded programming.
Hard to know what caused the crash without seeing the code. Can you share some?
Multithreaded programming is complex, and the question you should always ask is, do I really need it? You might be able to do without, and it will simplify things a lot.
Even if it's not strictly necessary in this case, it can still be a good occasion to learn/experiment.
In this case, I have a hard time imagining why having called rand() / srand() would lead to a crash later.
I would rather advise you double-check every freeing of resource that your child thread might still be using.
For example, if your AI thread uses any allegro function / data, the thread should already be stopped before allegro is shut down.
Note that even if you don't call al_uninstall_system(void) yourself, it will be called after you reach the end of main() (AFAIK it is using the atexit() system to do so)
In general, killing the thread should be one of the first things to do when you stop the program.
Hard to know what caused the crash without seeing the code. Can you share some?
Sorry, the code is way too huge to post.
the question you should always ask is, do I really need it? You might be able to do without, and it will simplify things a lot.
My game runs fine without it, but on really large maps the A.I. tends to take almost 1 second to calculate every move, making the whole game appears frozen. That's why I think using a separated thread for it became necessary.
In general, killing the thread should be one of the first things to do when you stop the program.
I call al_destroy_thread on my leave game routine, so it doesn't seem to be the case.
I'm testing the game again and not getting any chashes, it must have been a coincidence that something went wrong right after including the new srand call.