多个线程调用同一个 rand() 函数,如何让它们调用自己的 rand() 函数实例?

Multiple threads invoking the same rand() function, how do I make them call their own instance of rand() function?

我有一个关于低级别的多线程和函数调用如何工作的问题。如果我从多个线程调用 rand() 函数,它们是否访问 same 函数?它存储在内存中的什么位置?所有线程都访问函数的 相同 内存位置吗?如果它们都访问相同的内存位置,是否可能是两个线程同时访问同一个函数,所以一个线程会死锁或 bottleneck/slow 中断整个进程?

我想让我的线程完全并行,所以我希望它们调用它们自己的 rand() 函数实例。我该怎么做呢?

rand 函数使用静态内部状态,因此如果您从多个线程调用它,您可能会遇到竞争条件。

相反,如果您的系统支持,请使用 POSIX-defined rand_r() 函数。它采用在每次连续调用时更新的种子值的地址。然后每个线程都会将自己的种子值副本设置为某个初始值,而不是调用 srand.

所以不是这个:

srand(INITIAL_VALUE);
val = rand();
val = rand();
val = rand();
...

你会这样做:

unsigned int seed = INITIAL_VALUE;
val = rand_r(&seed);
val = rand_r(&seed);
val = rand_r(&seed);
...

I have a question about how multithreading and function calls at low-level work. If I call the rand() function from multiple threads, do they access the same function?

是的。他们都访问 rand 函数。

Where is it stored in the memory?

如果您所说的“它”是指 rand 函数的代码,那么它将与程序的其余代码一起存储在内存中。

Do all threads access the same memory location for the function? If they all access the same memory location, could it be that two threads are accessing the same function at the same time so one would deadlock or bottleneck/slow down the overall process?

代码从未被修改。两个线程访问内存中从未修改过的数据不会导致任何死锁、瓶颈或速度变慢。

I want to make my threads completely parallel, so I want them to call their own instance of the rand() function. How could I go about doing that?

函数的实例不是问题。问题是共享数据。访问共享数据的线程会导致性能问题,即使它们完全通过不同的函数访问共享数据。

最有可能的是,您根本不应该使用 rand,而是使用一些满足您的任何要求的代码。可能是 rand_r 做到了,但您最好寻找满足您所有要求的 random-number 生成器。