![]() |
|
Random number generator + multithreading problem |
Space cpp
Member #16,322
May 2016
|
Hello. My RNG function: 1int iRand(int min, int max)
2{
3 if (min >= max) return min;
4 int i = rand()%(max - min + 1);
5 return min + i;
6}
---------- |
Mark Oates
Member #1,146
March 2001
![]() |
Are you initializing the random numbers with srand? -- |
bamccaig
Member #7,536
July 2006
![]() |
Perhaps you need to reseed it on each thread? void srand(unsigned); Or seed it at all. Most people pass time as the seed value so it changes each time you run the program.
-- acc.js | al4anim - Allegro 4 Animation library | Allegro 5 VS/NuGet Guide | Allegro.cc Mockup | Allegro.cc <code> Tag | Allegro 4 Timer Example (w/ Semaphores) | Allegro 5 "Winpkg" (MSVC readme) | Bambot | Blog | C++ STL Container Flowchart | Castopulence Software | Check Return Values | Derail? | Is This A Discussion? Flow Chart | Filesystem Hierarchy Standard | Clean Code Talks - Global State and Singletons | How To Use Header Files | GNU/Linux (Debian, Fedora, Gentoo) | rot (rot13, rot47, rotN) | Streaming |
Space cpp
Member #16,322
May 2016
|
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. ---------- |
amarillion
Member #940
January 2001
![]() |
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. -- |
Audric
Member #907
January 2001
|
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. For example, if your AI thread uses any allegro function / data, the thread should already be stopped before allegro is shut down. In general, killing the thread should be one of the first things to do when you stop the program. |
Space cpp
Member #16,322
May 2016
|
amarillion said: Hard to know what caused the crash without seeing the code. Can you share some? Sorry, the code is way too huge to post. amarillion said: 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. Audric said: 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. ---------- |
|