代码之家  ›  专栏  ›  技术社区  ›  The Unfun Cat

openMP可以像多处理一样使用吗?

  •  0
  • The Unfun Cat  · 技术社区  · 6 年前

    multiprocess.map(f, list_of_cython_objects)
    

    像下面这样的东西行吗?为什么?我知道我必须创建一个指向cython对象的指针数组,我不能使用列表。

    from cython.parallel import prange, threadid
    
    with nogil, parallel():
    
        for i in prange(len(list_of_cython_objects), schedule='guided'):
            f(list_of_cython_objects[i])
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   DavidW    6 年前

    前提是 f cdef 的属性 cdef class )这样就可以很好地工作了。唯一需要GIL的是索引列表,你可以很容易地把它放到一个 with gil 阻止。

    from cython.parallel import prange, parallel
    
    cdef class C:
        cdef double x
    
        def __init__(self,x):
            self.x = x
    
    cdef void f(C c) nogil:
        c.x *= 2
    
    
    def test_function():
        list_of_cython_objects = [ C(x) for x in range(20) ]
        cdef int l = len(list_of_cython_objects)
        cdef int i
        cdef C c
        with nogil, parallel():
            for i in prange(l, schedule='guided'):
                with gil:
                    c = list_of_cython_objects[i]
                f(c)
    

    只要 块很小(就计算时间的比例而言),那么您应该可以获得预期的大部分并行化速度。