whether rand_r is real thread safe?

Posted by terry on Stack Overflow See other posts from Stack Overflow or by terry
Published on 2010-05-05T09:51:12Z Indexed on 2010/05/05 9:58 UTC
Read the original article Hit count: 172

Filed under:
|

Well, rand_r function is supposed to be a thread safe function. However, by its implementation, I cannot believe it could make itself not change by other threads. Suppose that two threads will invoke rand_r in the same time with the same variable seed. So read-write race will occur. The code rand_r implemented by glibc is listed below. Anybody knows why rand_r is called thread safe?

 int
    rand_r (unsigned int *seed)
    {
      unsigned int next = *seed;
      int result;

      next *= 1103515245;
      next += 12345;
      result = (unsigned int) (next / 65536) % 2048;

      next *= 1103515245;
      next += 12345;
      result <<= 10;
      result ^= (unsigned int) (next / 65536) % 1024;

      next *= 1103515245;
      next += 12345;
      result <<= 10;
      result ^= (unsigned int) (next / 65536) % 1024;

      *seed = next;

      return result;
    }

© Stack Overflow or respective owner

Related posts about c++

Related posts about c