Sunday, October 02, 2005

Yet another multithreading pitfall: random numbers

This one cost me a few hours to detect. Always remeber to initialize the stdlib random number engine for each thread with something like
/* initialize random generator */
srand ( time(NULL) );
otherwise they will all generate the same sequence of "random" numbers.

I wish I could avoid multithreading on this project, but I can't since it's a QT GUI and responsiveness is crucial to the end user.

On a side note: does anyone out there know of a compilation of common multithreading pitfalls floating around the net ?

2 comments:

Mathieu Fenniak said...

Did you encounter this problem while creating multiple threads, or while creating multiple processes? I can imagine this sort of behavior in the case of fork()ing a process, but I don't see why it would happen with multiple threads. A simple test seems to show that this is not the case in multithreading.

ricardo said...

It happened while creating a background worker thread on Win32 using QThread from Qt 4.0 (trolltech.com).