title: How do I use rand_r and how do I use it in a thread safe way?
body: <p>I am trying to learn how to use rand_r, and after reading <a href="https://stackoverflow.com/questions/2772090/whether-rand-r-is-real-thread-safe">this question</a> I am still a little confused, can someone please take a look and point out what I'm missing? To my understanding, rand_r takes a pointer to some value (or a piece of memory with some initial value) and use it to generate new numbers every time it is called. Each thread that calls rand_r should supply it with a unique pointer (or piece of memory) to get "actual random" numbers between different threads. That's why this:</p>
  
  <pre><code>int globalSeed;
  
  //thread 1
  rand_r(&amp;globalSeed);
  
  //thread 2
  rand_r(&amp;globalSeed);
  </code></pre>
  
  <p>is the wrong way of using it. If I have </p>
  
  <pre><code>int seed1,seed2;
  
  //thread 1
  rand_r(&amp;seed1);
  
  //thread 2
  rand_r(&amp;seed2);
  </code></pre>
  
  <p>this would be the right way to generate "true random" numbers between threads?</p>
  
  <hr>
  
  <p>EDIT: additional questions after reading answers to the above part: </p>
  
  <ol>
  <li>if in thread 1 I need a random
  number between 1 to n, should I do
  <code>(rand_r(&amp;seed1) % (n-1)) + 1</code> ? Or there is other common way of doing this?</li>
  <li>Is it right or normal if the memory for the seed is dynamically allocated?</li>
  </ol>