2015-08-28 21 views
5

我有一本字典,使用在用Cython字典,尤其是裏面nogil

my_dict = {'a':[1,2,3], 'b':[4,5] , 'c':[7,1,2]) 

我想用這個字典中的用Cython內nogil功能。所以,我試圖宣佈它爲

cdef dict cy_dict = my_dict 

到目前爲止還沒有。

現在我需要迭代my_dict的鍵,如果值在列表中,請遍歷它。在Python中,它很容易,如下所示:

for key in my_dict: 
     if isinstance(my_dict[key], (list, tuple)): 
      ###### Iterate over the value of the list or tuple 
      for value in list: 
       ## Do some over operation. 

但是,在Cython裏面,我想要在nogil裏面實現相同的功能。因爲,python對象不允許在nogil內部,我都被卡在這裏。

with nogil: 
    #### same implementation of the same in Cython 

任何人都可以幫我嗎?

回答

16

唯一真正明智的選擇是接受你需要GIL,不幸的是。涉及C++地圖的選擇不太明智,但可能很難申請您的具體情況。

您可以使用with gil:重新獲取GIL。這裏有一個明顯的開銷(使用GIL的部分不能並行執行,並且可能會有等待GIL的延遲)。然而,如果詞典操縱是一塊較大的用Cython碼的一小塊,這可能不是太差:

with nogil: 
    # some large chunk of computationally intensive code goes here 
    with gil: 
    # your dictionary code 
    # more computationally intensive stuff here 

其他較少明智的選擇是使用C++圖(沿側其他C++標準庫數據類型)。 Cython可以包裝這些並自動轉換它們。爲了讓基於您的數據。例如一個簡單的例子:

from libcpp.map cimport map 
from libcpp.string cimport string 
from libcpp.vector cimport vector 
from cython.operator cimport dereference, preincrement 

def f(): 
    my_dict = {'a':[1,2,3], 'b':[4,5] , 'c':[7,1,2]} 
    # the following conversion has an computational cost to it 
    # and must be done with the GIL. Depending on your design 
    # you might be able to ensure it's only done once so that the 
    # cost doesn't matter much 
    cdef map[string,vector[int]] m = my_dict 

    # cdef statements can't go inside no gil, but much of the work can 
    cdef map[string,vector[int]].iterator end = m.end() 
    cdef map[string,vector[int]].iterator it = m.begin() 

    cdef int total_length = 0 

    with nogil: # all this stuff can now go inside nogil 
     while it != end: 
      total_length += dereference(it).second.size() 
      preincrement(it) 

    print total_length 

(你需要language='c++'編譯這個)。

這樣做的一個明顯的缺點是,字典中的數據類型必須事先知道(它不能是一個任意的Python對象)。但是,由於您無法操作nogil塊內的任意Python對象,所以無論如何您都受到相當的限制。

+0

謝謝。讓我看看。數據類型在字典裏面,我會把它保存爲列表。對於編譯,我可以遵循正常的Cython方式嗎? –

+0

您需要按照[此處](http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html#specify-language-in-setup-py)中所述的方式指定語言,但除此之外它應該正常工作辦法。 – DavidW

+0

哦,真抱歉。我刪除了評論,因爲我發現它的工作。對不起, –

相關問題