So i’ve been writing some applications in C and using OpenMP for parallelization. I implemented a Monte-Carlo Pi estimate and found that the normal rand() function is not reentrent and thread-safe. The recommendation is to use the drand48_r option.
Now here is the problem, my application compiles fine on Linux eg. Ubuntu, Fedora and CentOS but does not compile on Mac OS X. The compile error on OS X is.
simple.c:7: error: storage size of ‘randBuffer’ isn’t known
The code used as the simple example is:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
double x;
struct drand48_data randBuffer;
srand48_r(time(NULL), &randBuffer);
drand48_r(&randBuffer, &x);
printf("Random number: %f\n", x);
return EXIT_SUCCESS;
}
I read up about it and I found a note in the man pages that,
These functions are GNU extensions and are not portable.
Here is a link to it: http://www.kernel.org/doc/man-pages/online/pages/man3/drand48_r.3.html
So I have a number of questions;
- What are GNU extensions and what makes it non portable?
- What alternatives do I have for random number generation on OS X that is also thread-safe?
Well that is about it.
The example is compiled with gcc as,
gcc simple.c -o simple
I don’t really see the gain of using
drand48_rovererand48.erand48has the same type of random generator asdrand48but compared to that receives the state of the random generator as a function parameter, so it perfectly does the job.The
_rextensions store the result in place (the second parameter) and return an error code that is always guaranteed to be0. I don’t see much use in all of this. I’d stick to the POSIX interfaces (in particularerand48).