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

标签 c multithreading low-level

我有一个关于低级多线程和函数调用如何工作的问题。如果我调用 rand()来自多个线程的函数,它们是否访问相同的函数?它存储在内存的什么地方?所有线程是否都访问该函数的相同内存位置?如果它们都访问相同的内存位置,是否两个线程同时访问同一个函数,因此会出现死锁或瓶颈/减慢整个过程?

我想让我的线程完全并行,所以我希望它们调用自己的 rand() 实例功能。我怎样才能做到这一点?

最佳答案

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?

如果“it”指的是 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 可以做到这一点,但您最好寻找一个能够满足您的任何要求的随机数生成器。

关于c - 多个线程调用同一个 rand() 函数,如何让它们调用自己的 rand() 函数实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71345304/

相关文章:

python - Numpy:随机种子和多线程导致不同的结果

c++ - 为什么在此代码块中使用 condition_variable?

大于2GB的SD卡的Android低级读取

c - 为什么我们不能通过简单地将值分配给新变量来复制文件描述符?

c - 用户定义命令

c - 重复使用客户端TCP套接字进行多个HTTP连接

c - strcat 给出意外结果

c - 如何在 C 程序中的 char 数组中分配输入(来自 echo 命令)

java - 在 spring boot Rest API 中关闭 ExecutorService

java - 分配延迟似乎很高,为什么?