Reputation: 918
I have a QT app, running 2 more threads.
Inside the threads I use the qrand function to generate a random number. The following is the code used to get the number, where m_fluctuations max is a double.
int fluctuate = qrand() % (int)(m_FluctuationMax * 100);
I tried adding the following code in the main thread, and also inside the thread classes.
QTime now = QTime::currentTime();
qsrand(now.msec());
Now the problem is, that the values being generated are always the same, each time the application is started.
Shouldn't they be different, since the seed is set by 'currentTime()'.
Thanks
Upvotes: 4
Views: 23506
Reputation: 132
This may help anyone who happened to have a similar problem:
qsrand(static_cast<quint64>(QTime::currentTime().msecsSinceStartOfDay()));
array<int, 5> arr = {qrand(), qrand(), qrand(), qrand(), qrand()};
for(auto i : arr)
cout << i << endl;
Upvotes: 4
Reputation: 881373
The first thing I'd be checking is the value of now.msec()
. It only returns the millisecond part of the current time and the doco states:
Note that the accuracy depends on the accuracy of the underlying operating system; not all systems provide 1-millisecond accuracy.
It may be that your platform always returns the same value for msec()
. If that's the case, you could try using minutes and seconds combined somehow (assuming you're not running your code multiple times every second).
You haven't stated which platform you're running on but the Qt source code only supports sub-second resolution if either Q_OS_WIN
or Q_OS_UNIX
is set.
Keep in mind that the random numbers are per-thread so you should probably do the qsrand
in each thread, lest it be automatically seeded with 1.
Upvotes: 2
Reputation: 152817
I had my qsrand() in the thread/class constructor. When i moved it to the run() function, it started to work randomly. Not sure why it would not work from the constructor though.
qsrand()
uses thread-local storage to store the seed which is actually the pseudorandom number generator state that also gets updated on each call to qrand()
. If you seed the PRNG outside the thread where you will be using it, that seed does not influence the outcome. Thread-local storage usually defaults to zero so that way you would get the same sequence of pseudorandoms every time because the seed is always the same.
Upvotes: 2
Reputation: 918
I had my qsrand() in the thread/class constructor. When i moved it to the run() function, it started to work randomly. Not sure why it would not work from the constructor though. Thanks everyone for your help.
Upvotes: 8