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
For random number generator in C, we use rand() and srand() functions that can generate the same and different random numbers on execution.
Can we write multithreading programs in C? Unlike Java, multithreading is not supported by the language standard. POSIX Threads (or Pthreads) is a POSIX standard for threads.
The function rand() is not reentrant or thread-safe, since it uses hidden state that is modified on each call.
Along with this, C# provides an option to execute the code that can be run in parallel using a multithreading concept, where the process/application can have multiple threads invoked within it.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With