具有多个线程的rand() [英] rand() with multiple threads

查看:109
本文介绍了具有多个线程的rand()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究两个线程,试图在main()中生成一次seed(time(null))来生成随机数.程序不断出现分段错误,直到我发现使用线程时,我们必须在其自己的例程中为所有线程生成随机数,然后再没有seg错误.

I was working on two threads trying to generate random numbers seeding once seed(time(null)) in main(). Program got segmentation fault continuously until I figured out that when working with threads we must generate random numbers for all threads in their own routines and there was no seg fault then.

我试图在Google上找到答案,以了解为什么我们必须为所有线程单独播种,但没有找到足够有说服力的答案.有人可以解释一下吗? 谢谢!

I tried to find answer on google as to why do we have to seed independently for all threads but did not find enough convincing answers. Could anyone please explain? Thanks!!

推荐答案

给您一个简短的答案:

rand()不是线程安全的.

rand() is not thread safe.

不应在没有显式关键部分的情况下从多个线程调用它.

It should not be called from multiple threads without explicit critical section.

这篇关于具有多个线程的rand()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆