多个线程调用同一个 rand() 函数,如何让它们调用自己的 rand() 函数实例?
我有一个关于低级多线程和函数调用如何工作的问题。如果我从多个线程调用 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? Where is it stored in the memory? 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。它们都访问
rand
函数。如果“it”指的是
rand
函数的代码,那么它会与程序的其余代码一起存储在内存中。代码永远不会被修改。两个线程访问内存中从未修改的数据不会导致任何死锁、瓶颈或速度减慢。
函数的实例不是问题。问题是共享数据。访问共享数据的线程会导致性能问题,即使它们完全通过不同的函数访问共享数据。
最有可能的是,您根本不应该使用
rand
并使用一些可以满足您的任何要求的代码。也许rand_r
可以做到这一点,但您最好寻找一个能够满足您的任何要求的随机数生成器。Yes. They all access the
rand
function.If by "it", you mean the code for the
rand
function, then it's stored in memory with the rest of the program's code.The code is never modified. Two threads accessing data in memory that is never modified do not cause any deadlock, bottleneck, or slow down.
The instance of the function isn't the issue. The issue is the shared data. Threads accessing shared data will cause performance issues, even if they access the shared data through different functions entirely.
Most likely, you should just not use
rand
at all and use some code that meets whatever requirements you have. It may be thatrand_r
does it, but you're probably better off looking for a random-number generator that meets whatever requirements you have.rand 函数使用静态内部状态,因此如果从多个线程调用它,可能会出现竞争条件。
相反,请使用 POSIX 定义的
rand_r()
< /a> 函数(如果您的系统支持)。它采用在每次连续调用时更新的种子值的地址。然后,每个线程会将自己的种子值副本设置为某个初始值,而不是调用 srand。因此,
您可以这样做:
The
rand
function uses static internal state, so if you call it from multiple threads you could get a race condition.Instead, use the POSIX-defined
rand_r()
function if your system supports it. It takes the address of a seed value that is updated on each successive call. Then each thread would set its own copy of the seed value to some initial value instead of callingsrand
.So instead of this:
You would do this: