简体   繁体   English

Windows的rand_s线程安全吗?

[英]Is Windows' rand_s thread-safe?

Just as in title. 就像标题一样。 Is suspect it is, but I couldn't find it anywhere explicitly stated. 怀疑它是,但我无法在任何明确说明的地方找到它。 And for this property I wouldn't like to rely on speculations. 对于这个属性,我不想依赖猜测。

If you use the multithreaded version of the CRT, all functions are thread safe, because any thread-specific information is stored in TLS . 如果使用CRT的多线程版本,则所有函数都是线程安全的,因为任何特定于线程的信息都存储在TLS中 rand_s actually doesn't use state information in the first place, since it just calls an OS API, so question of thread-safety doesn't arise for rand_s. rand_s实际上并不首先使用状态信息,因为它只调用OS API,因此rand_s不会出现线程安全问题。 rand(), however depends on a seed value to generate a random number. 然而,rand()依赖于种子值来生成随机数。

Chris said: rand() is not thread-safe because its internal state is static, but rand_s() should be thread-safe, however. Chris说: rand()不是线程安全的,因为它的内部状态是静态的,但是rand_s()应该是线程安全的。

Jeff added however that with the multithreaded version of MSVCRT, rand() 's state is held in thread-local storage, so it's okay still. 但是Jeff补充说,使用多线程版本的MSVCRT, rand()的状态保存在线程本地存储中,所以它仍然可以。

Visual Studio comes with the source to the runtime library. Visual Studio附带了运行时库的源代码。 While some of it can be rather painful to wade through, rand_s() is pretty simple. 虽然其中一些内容可能相当痛苦,但rand_s()非常简单。

All rand_s() does is call SystemFunction036() in ADVAPI32.DLL to get the random value. 所有rand_s()都在ADVAPI32.DLL中调用SystemFunction036()来获取随机值。 Anything in ADVAPI32.DLL should be thread-safe. ADVAPI32.DLL中的任何内容都应该是线程安全的。

For its part, rand_s() gets the pointer to that function in a thread-safe manner. 就其本身而言,rand_s()以线程安全的方式获取指向该函数的指针。

I don't know if rand_s is thread-safe, but it seems like it probably is, since it seems to make a round-trip to the OS for entropy. 我不知道rand_s是否是线程安全的,但它似乎可能是,因为它似乎是为了进行熵的操作系统的往返。 (as long as you link to the VC++ multi-thread CRT, all bets are off if you link to the single-thread one) (只要链接到VC ++多线程CRT,如果链接到单线程,则所有投注都会关闭)

If it's supported by windows CRT, you can try a call to rand_r which is the posix reentrant version of rand. 如果Windows CRT支持它,你可以尝试调用rand_r,这是rand的posix可重入版本。 OR even better boost::random, if you're already using boost. 或者甚至更好的boost :: random,如果你已经使用了boost。

considering how pervasive multi-threading will be soon, no one should be using rand() anymore in new code - always try to use rand_r/rand_s/boost/various platform-dependent secure rands/etc. 考虑到普遍的多线程将很快,没有人应该在新代码中使用rand() - 总是尝试使用rand_r / rand_s / boost /各种平台相关的安全rands /等。

我想不出为什么rand_s()甚至rand()不是线程安全的任何原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM