cython的线程安全随机数生成 [英] thread-safe random number generation with cython

查看:75
本文介绍了cython的线程安全随机数生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对我所做的事情进行cythonise,这涉及在并行化循环内生成随机数.我想使用mtrand,但是由于它是Python代码,因此无法在nogil块中运行,并且由于某些原因,mtrand的.pyx没有公开供我们其他人使用.

I am trying to cythonise something I did which involves random number generation inside a parallelised loop. I wanted to use mtrand but since it's Python code it can't work from a nogil block and for some reason mtrand's .pyx isn't exposed for the rest of us to use.

我知道我可以使用rand或任何其他C RNG(例如gsl);还有更标准的方法吗?

I know I can use rand or any other C RNG (e.g. gsl); is there a more standard way?

推荐答案

您已正确总结了这种情况.在撰写本文时,您可以做以下三件事之一:

You have summed up the situation correctly. As of this writing, you can do one of three things:

  • 修改NumPy以允许共享mtrand.pxd中的声明

  • Modify NumPy to allow sharing the declarations in mtrand.pxd

通过NumPy的默认生成器使用其随机生成器(也许您可以在nogil块之外预先存储所有随机数?)

Use NumPy's random generators through their default interface (perhaps you could store all the random numbers in advance outside of the nogil block?)

使用用C编写的随机数生成器(如果要让Cython生成C ++代码,则可以使用C ++).

Use a random number generator written in C (or possibly C++ if you are having Cython generate C++ code).

老实说,我可能会做最后一个.如果您可以使用C ++ 11,则C ++标准库中现在包含了一些不错的随机数生成器.

Honestly, I'd probably do the last one. If you can use C++ 11, there are several good random number generators now included in the C++ standard library that you could use.

这篇关于cython的线程安全随机数生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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