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
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
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.
gsl_rng_alloc). That is, thread safety is achieved by having multiple random number generators, each with their own state, rather than by locking the state each time the generator is used.rand returns unexpected results, what's the problem?rand() implementation would also give the exact same random values twice, with some probability. But in principle you're right, because with a correct rand() it's a known probability, and here it isn't. If it's used for cryptography, it can actually matter.If you just want some random numbers and do not care whether the random number serials be 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;
}
A thing of truth and beauty;
http://en.wikipedia.org/wiki/Mersenne_twister
Write your own RNG.
(Apologies. I've just looked at that wiki page. Last I looked, a while back, it was fine; you could read it and implement the twister. Now it's a bunch of degree level maths which explains absolutely nothing to anyone, barring the subset of the population who spent four years at University studying mathmathics. I see this happen a lot on the wiki :-(