1. 2009
    Mar
    10

    How to use random_r

    The random_r function, a GNU addition to the standard C library, allows you to use a pseudorandom number generator whose persistent state is stored in an area of memory managed by your program, rather than the system. It’s useful when you want to generate pseudorandom numbers quickly, without taking the time to synchronize access to the PRNG state, among other uses.

    This function is a little esoteric, judging by the fact that I couldn’t find any clear example of how to use it in a multithreaded program when I was trying to fix up a simulation today. Here’s an example (error checking omitted):

    #include <pthread.h>
    #include <stdlib.h>
    #define NTHREADS 4
    #define PRNG_BUFSZ 32
    

    PRNG_BUFSZ stands for “pseudorandom number generator buffer size” which is exactly what it sounds like, the size (in bytes) of the state buffer allocated to each PRNG. Sure, I could have written BUFFER_SIZE but C programmers write in this abbreviated Hebrew-like code so much I’m surprised the language still includes vowels. Anyway, whatever you call it, this number must be at least 8. The larger this size, the more complex the pseudorandom number sequence will be.

    void* thread_run(void* arg) {
        int …