jeudi 25 janvier 2018

Random function call from multiple threads in C++/QT

I have a multi-thread QT application that sometimes need a random alphanumeric string from one of its threads (some threads start at application startup, others start or die during lifetime), and I would like to obtain that by calling a function defined in a common header, to avoid code replication.

Here there's a code snippet:

QString generateRandomAlphanumericString(int length)
{
    qsrand(static_cast<uint>(QTime::currentTime().msec())); //bad
    QString randomAS = QString();

    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < length; ++i)
        randomAS[i] = alphanum[qrand() % (sizeof(alphanum) - 1)];

    return randomAS;
}

I initially did some mistakes.

At the beginning I called qsrand(static_cast<uint>(QTime::currentTime().msec())); in the main function, but I've learned that it should be done per-thread.

Then I put the qsrand call in the function above, but it's not correct.

Please consider that at program startup many threads start "together", so if I initialize the seed with current time in msec the seed is the same among them.

Is there a way to change that function accordingly without modify all points in my application where a thread starts its life? Any implementation done in pure C++ (without the use of QT) is fine. Could the new random C++11 library help in some way to achieve my task?




Aucun commentaire:

Enregistrer un commentaire