Salih Erikci Salih Erikci - 4 years ago 182
C Question

Creating random numbers in a multithreaded program in C

I am writing a program where there are worker threads which create random numbers
from 0 to 3
from 0 to x-1(a variable)

what i need to learn is that how can i produce these random numbers in C.

I am using gcc compiler and working on Ubuntu 11.10

Answer Source

rand() & srand() are not the ones that can be used safely in that case.

They both are neither re-entrant nor threadsafe. Generally speaking, neither C or the C++ standards pose any requirements about thread safety on any of the standard library functions.
Some implementations may indeed provide thread safe versions but it is not mandated by the standard.

To be able to use a random number generator in multithreaded environment You will need a implementation that allows passing in the state. This way, you can keep one state value per thread, and generate good quality random numbers without requiring synchronization.

The C standard library does not provide any choices. That makes 100% portability rather impossible.The choice of usage would then depend on your environment which you should mention as a part of your question to get accurate answers.

Have a look at GNU Scientific Library which claims to provide MultiThreaded Random Number generator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download