rand_r函数被认为是一个线程安全的函数。然而,通过它的实现,我不相信它能够避免被其他线程改变。 假设两个线程将在相同的时间使用相同的变量种子调用rand_r函数。 这样就会发生读写竞争。 glibc实现的rand_r代码如下所示。有人知道为什么rand_r被称为线程安全吗?
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;
}