简体   繁体   English

Cython中的并行性不起作用

[英]Parallelism in Cython does not work

I have a following Cython code: 我有一个以下的Cython代码:

from cython import parallel
from libc.stdio cimport printf

def test_func():
    cdef int thread_id = -1
    with nogil, parallel.parallel(num_threads=10):
        thread_id = parallel.threadid()
        printf("Thread ID: %d\n", thread_id)

However, it always starts only one thread, ie output is always only 但是,它始终只启动一个线程,即始终只输出

Thread ID: 0

What am I doing wrong to get multithreading? 我在做多线程时做错了什么?

Cython uses OpenMP for it's multithreading capabilities. Cython使用OpenMP来实现多线程功能。

To enable OpenMP the compiler will need an extra flag to be passed to it while compiling and linking otherwise the parallel part of your code will be ignored. 要启用OpenMP,编译器将需要在编译和链接时传递一个额外的标志,否则将忽略代码的并行部分。

The flags for some popular compilers are as follows: 一些流行的编译器的标志如下:

  • GCC = -fopenmp GCC = -fopenmp
  • MSVC = /openmp MSVC = / openmp
  • icc = -openmp icc = -openmp

Assuming that you have saved your function in the file test.pyx the following setup.py should work if you are using GCC. 假设您已将函数保存在test.pyx文件中,则在使用GCC时,以下setup.py应该可以正常工作。

from distutils.core import setup, Extension
from Cython.Build import cythonize

extensions = [Extension(
                "test",
                sources=["test.pyx"],
                extra_compile_args=["-fopenmp"],
                extra_link_args=["-fopenmp"]
            )]

setup(
    ext_modules = cythonize(extensions)
)

Once compiled like that the code should spawn 10 threads when run: 一旦这样编译,代码应该在运行时产生10个线程:

In [1]: import test

In [2]: test.test_func()
Thread ID: 9
Thread ID: 1
Thread ID: 6
Thread ID: 7
Thread ID: 3
Thread ID: 8
Thread ID: 5
Thread ID: 4
Thread ID: 0
Thread ID: 2

If you want some more information than this page in the cython docs has a good basic guide of how to use parallelism with cython. 如果你想在cython文档中获得比这个页面更多的信息,那么有一个很好的基本指南,介绍如何使用cython的并行性。

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

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