Creating random numbers in a multi-threaded program in C

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

what I need to know is how I can produce these random numbers in C.

I am using gcc compiler and working on Ubuntu 11.10

+4
source share
5 answers

rand() and srand() cannot be used safely in this case.

Both of them are neither repeaters nor thread safe . Generally speaking, neither C standards nor C ++ standards impose any thread safety requirements in any of the standard library functions.
Some implementations may indeed provide thread safe versions, but a standard is not provided.

To use a random number generator in a multi-threaded environment, you will need an implementation that allows you to pass to state. Thus, you can save a single state value for the stream and generate high-quality random numbers without the need for synchronization.

The standard C library does not provide any options. This makes portability 100% impossible. The choice of use will depend on your environment, which you must indicate as part of your question in order to get accurate answers.

Check out the GNU Science Library , which claims to provide the MultiThreaded Random Number Generator .

+7
source

If you just need some random numbers and don't care if the serial numbers of the random numbers are generated independently or not, you can still use rand() and srand() .

  #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <unistd.h> void* cb1(void*) { while(1) { printf("cb1, rand:%d\n",rand()); sleep(1); } } void* cb2(void*) { while(1) { printf("cb2, rand:%d\n",rand()); sleep(1); } } int main() { pthread_t th1, th2; srand(1); pthread_create(&th1, NULL, cb1, NULL); pthread_create(&th2, NULL, cb2, NULL); pthread_join(th1, NULL); pthread_join(th2, NULL); return 0; } 
+1
source

Use rand_r() (see rand (3))

The rand_r () function is supplied with a pointer to an unsigned int, for use as a state.

It is reentrant and accepts a seed as input, so threads can manage their seeds separately.

0
source

A thing of truth and beauty;

http://en.wikipedia.org/wiki/Mersenne_twister

Write your own RNG.

(Apologies ... I just looked at this wiki page. The last thing I looked a while ago was great, you could read it and implement a twister. Now this is a bunch of math level that doesn't explain anything to anyone , with the exception of a subgroup of the population that worked at the university for four years studying math. I see this happening on the wiki:

0
source

A simple version without error checking using C11 threads.h would look like this:

 mtx_t rand_mtx; //run only once. int rand_init(int seed) { srand(seed); mtx_init(&rand_mtx, mtx_plain); } int synced_rand() { mtx_lock(&rand_mtx); int r = rand(); mtx_unlock(&rand_mtx); return r; } 
0
source

Source: https://habr.com/ru/post/1389802/


All Articles