PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

SRAND( ) / RAND( ) issue

Does GapiDraw happen to reseed the pseudorandom number generator with SRAND(val) on a periodic basis? The reason I'm asking is that unless I reseed prior to making a RAND( ) call, I get the same random number sequence back all the time. If I make the SRAND(GetTickCount()) call at the start of the application (this is using the CMyApplication framework), it has no effect on the return value of RAND( ). Here's an example :

Using the CMyApplication framework (I used the Simple sample program supplied with 1.04) place

DWORD dwSeed = GetTickCount();
srand(dwSeed);

just before "return simple.Run();" in WinMain( ).

This will seed the random number generator. You should only have to do this once at the start of an application. Multiple SRAND( ) calls are highly discouraged.

Now, in ProcessNextFrame( ), place this line at the top of the method

int r = (rand() % 10) + 1;

This will generate a random number from 1 to 10. Pretty simple stuff...

Launch the debugger and set a breakpoint on the rand call. Make note of the value that is returned and restart the debugger several times. You'll find that the random number is the same everytime.

Now, copy the srand code just before the rand line and run the debugger... random numbers as expected.

This says to me that srand is being reseeded with a value by GapiDraw every frame. I don't see this problem with a simple application outside the CMyApplication framework. Is there something I'm missing here?

Thanks for any insight on this problem... -- GR
I had another thought on this issue - how does multithreading effect SRAND/RAND? I'm going to see what I can come up with on this...

-- GR
Guest · 25 Sep 2002, 16:18 UTC — Rand
Use your own rand function - very helpfull if you have to port your game to another platform or even another C library and want your random number generator behave exactly the same in ever case.
From what I've found, the seed value for rand is set in the parent thread, and carried through all child threads. This explains why I see the random numbers switching back to their old pattern depending on whether I reseed before each rand call or not. If I can find the proper way to seed the main thread, that seed value will propagate through the child threads and rand will work correctly.
I think I will end up writing my own rand functions as suggested above. The more I read on the subject of rand and threads the more conflicting info I'm finding. :(
As a followup...

I modified the rand_num class from the XKobo source to fit my needs, and am using it to generate random numbers. This is now working correctly since it doesn't rely on srand/rand to create the values. I think that this rand issue _could_ be resolved in GapiDraw if the main thread initialized the seed value with srand(GetTickCounter()) [or srand((unsigned)time(NULL))] before creating any other threads. The seed value _should_ propogate through the other threads and provide a base for rand to work from.

-- GR
ppcStudios · 10 Oct 2002, 20:18 UTC — SRAND( ) revisited
I've been working using the XKobo random number generator to finish up work I'm doing on a Pachisi game, but after using it for several weeks I'm not happy with its performance at all. Random numbers are simply sequential (in a fashion) and its guaranteed you will _never_ get a duplicate result in calls to the method (eg never roll a double for example on 2 dice). I can reseed the the generator every time I want a random number and that works fine on desktop PCs, but not at all on pocket PCs. So, I'm now looking at other alternatives for random numbers.

What is everyone here using to generate random numbers in the GapiDraw framework?

-- GR
I would suggest you check the Mersenne Twister methode for generating random numbers. Just search for it on Google and you will find lot of resources. (If you want I can send you mine..).

I have sucessfully used it on the GBA game I did some time back.

best,

Sam
Thanks for the suggestion Sam. I took a look at this RNG and figured since it would take me a while to understand the code for it I would spend a bit of time trying to figure out how to make the srand/rand pair work under GapiDraw. Here's what I found:

1) srand/rand is thread dependent. In other words, if you have multiple threads, you have to call srand for each thread otherwise rand thinks you did an srand(1) for that thread.

2) InitInstance() and ProcessNextFrame() are on separate threads. I probably read this somewhere before, but I can't find where. This is key to making srand/rand work correctly.

3) Calling srand in InitInstance (where you would think to normally do it) results in setting the seed for the primary thread (well, at least NOT for the thread you want it to seed).

4) Calling srand in ProcessNextFrame results in setting the seed for the thread of interest - your game loop thread.

5) Calling srand multiple times is a no-no. Only call it once in ProcessNextFrame - set a static bool that says you've already initialized the seed.

So, I finally got it working correctly. If I find any other oddities, I'll post it here and on my website. Thanks for everyone's help on this. =)

-- GR
Isn't all this getting complicated? Why do you use threads in the first place?

My experience with threads is that they bring more problems then they solve. The only place I could see some benefits to them is when implementing a thread pool for some server software.

On a PPC, it is overkill.
I don't agree..

Threading has three advantages:
(1) Simplicity. Using two threads you can actually use time-based animation sequences without having to return from ProcessNextFrame on every update. This "linear programming model" is proclaimed as superior by many game developers, and articles on it is everywhere, from gamedev.net to the book "Game programming gems2".
(2) Networking. If you code real-time multiplayer games it's nice to be able to let the pump receive data multiple times during each frame pass (this is especially true for the Pocket PC). If you use multiple threads, yielding control to other threads will also let the key and stylus input to update contiously, saving time on each sleep between frames.
(3) Windowed application support. Basically it's necessary to use multiple threads for real-time windowed applications. Otherwise your application would get "stalled" by window messages when the window is moved around etc (one could increase the process priority, but that's not recommended). It's no use to create two application shells, one for PocketPCs and one for the Stationary PCs, so using multiple threads on both is (IMHO) the best option.

Using multiple threads by the way is a must for Pocket PC applications if you use networking. The incoming UDP buffer of 4kb is so quickly overrun that you need at least a minimum of 3 networking threads to run even a simple UDP sender/receiver. So there are definitely a need for threading models on PocketPCs, other than in server oriented thread pools.

Updated: Oh, one final thing. Designing the multithreaded model I actually looked at existing games for the PC such as DiabloII to see how they implemented their threading models. Most games used a standard priority thread responsible for the main window, with other higher prioritized threads doing the actual game loop...

Threading has three advantages:
(1) Simplicity. (...) This "linear programming model" is proclaimed as superior by many game developers, and articles on it is everywhere, from gamedev.net to the book "Game programming gems2".


Well threads don't simplify design, quite the contrary, they add complexity. They also imply more code for synchronization and thus a program using threads can potentially contain more bugs. Threads being a "superior programming model" is highly subjective. I have the first two Game Programming Gems right here next to me, and they contain mostly incomplete and plainly wrong articles. Although there is still a few gems in there. I am a game programmer and I avoid threads when there is another way. I am currently working on Homeworld 2 (heavy graphics, sound processing, networking code, and so on), there is only one thread. Yet, it works very well. There is no need to synchronize anything, which simplifies the design (it ain't the other way around).


(2) Networking. If you code real-time multiplayer games it's nice to be able to let the pump receive data multiple times during each frame pass (this is especially true for the Pocket PC).


Yes, I agree. Low-level networking code really benefits from running in a separate thread, although it is not strictly necessary. But higher-level networking code should be in the main thread. The fact remains that you must provide synchronization to some kind of packet buffer somewhere, and this adds complexity.


(3) Windowed application support. Basically it's necessary to use multiple threads for real-time windowed applications. Otherwise your application would get "stalled" by window messages when the window is moved around etc (one could increase the process priority, but that's not recommended).

That's true... Only if your drawing is taking a lot of time (>0.1 sec?). An easier solution is to pause the game while the window is being moved. In any case, I have yet to see how I can move windows on my PPC.


Updated: Oh, one final thing. Designing the multithreaded model I actually looked at existing games for the PC such as DiabloII to see how they implemented their threading models. Most games used a standard priority thread responsible for the main window, with other higher prioritized threads doing the actual game loop...


The fact that Diablo II uses threads doesn't mean they are good. The fact that multiple games use them or that there is tons of articles on Gamedev.net don't mean anything. As far as I know, Diablo II has been in development forever. Like most games these days... Sigh. I find the game programmers to be quite a few years behind other programmers.

If you want one last example where threads make the design more complicated, look no further then this threads. How much time did ppcStudios spent debugging this and trying to figure it out why rand() didn't work as expected? How about his solution? Don't tell me it simplified his design/development process.

It is my experience that every multi-threaded program takes more time to design, implement and debug. They also have more code and (potentially) more bugs. I've work on multiple multithreaded systems in the past, and I don't want to go back there. One last thing, you mentionned sleep() somewhere, well... That's another issue with threads: you always end up waiting somewhere... So basically you are not getting the most out of your processor.

Finally, one positive comment for threads: they are just damn cool.
Many people would have either ignored or not noticed that rand wasn't working correctly. Others would opt for implementing their own RNG solution. I'm just happen to be the kind of person who will beat a horse to death until I understand the problem well enough to either solve it or acknowledge that I need to find another solution. The srand/rand issue was no fault of the GapiDraw design, rather of my own failing to understand the problem well enough to solve it. As for making my design more complicated, I can't say that it did as it only required a single boolean test to ensure I don't fire srand off more than once per run.

Interesting discussion of thread philosophy in any case.

-- GR
I never said anything about GapiDraw, I was just wondering why you were using threads... Maybe there is an alternative solution?
I re-read the thread and just found out that threads are part of GapiDraw. I was unaware of that and though ppcStudios was creating threads himself.

Johan, my comments may have carried the wrong tone because of that, and I sincerely apologize. It was in no way my intention to challenge your design.

I still believe threads sound nice from a theorical point of view. But my practical experience with them have teached me to stay away as much as possible. Nevertheless, I would definitely use them for low-level networking code and for a windowed application that needs to run interactively.
No need to apologize.. I never get much comments regarding the design of GapiDraw anyways, so it was very welcome!

The main reason threads are there is for the game to run nice when windowed on Stationary PCs (a case where you also would use threads). While this may not be critical to many, to me it was so simply because I use GapiDraw myself to develop multiplayer games. Pausing the games on all peers because one guy moved the window was not an option.

GapiDraw will from the next version no longer be released as a "pure" PocketPC/Smartphone library. It will be released to compete with Stationary SDKs like libSDL and Clanlib. Performance of the next version will simply be the best in the industry (on Stationary PCs). Many people are today using it to create only Stationary Apps, and while it may be a little more cumbersome if you only want to create a PocketPC target, it greatly simplifies work to have one library that runs hardware-accelerated in a window AND on the PocketPC using just one code base. If it works on the desktop you are almost guaranteed that it works on the PocketPC (if you avoid mem%4 DWORD storage etc which are errors not related to the game sdk but the device itself).

My 30 students who began this autumn had no problems with using the two threads. Not a single error in so far over 40 applications created by the students were related to this. Also, all students recompiled their games for the PocketPCs AFTER they had finished developing the windowed PC version. Not a problem so far. While threads may complicate things a little bit, game development today is still far much easier than it was back in the eighties (I mean, if students can create cross-platform games such as this from scratch in one week then there really is no issue: http://www.gapidraw.com/mobile/lab2.html ) Please do download the game and try it out.. Development time: less that 5 working days... :)
ppcstudios: Since I wasn't aware that srand was set on a per-thread basis (I thought it was per-process), I am thinking of "moving" InitInstance and CreateSurfaces so they are called by the same thread as ProcessNextFrame in the next GapiDraw. I think this would help with other systems such as sound as well...

Nice work on your developer pages!
Pejo Software - Per · 14 Oct 2002, 20:57 UTC
I must agree with Kzinti about what he says on the complexity of threads. It has actually happened quite a few time that I had to correct other people's sloppy use of threads. The bugs you can get when missusing threads are of the worst kind! They tend to be very irregular and hard to track. You also often find them very late. I am not saying that threads are all bad, sometimes they really simplifies things.
I really like GapiDraw's core functionality and I really hope that you try to keep the modular (or layered) approach separating the primitives from the application framework.
It would also be nice if you could have an option in the framework to use a single threaded approach or at least make it easy to incorporate that in to your framework. If you should try to make a game library that will be truly cross-platform (or easy to port) it might be good to give this some thought. Some targets for example doesn't have threads.