2010-10-13 18 views
2

線程我寫了一個Python腳本: 1.提交的搜索查詢 2.等待結果 3.解析返回的結果(XML)Python的隊列 - 綁定到一個核心

我所使用的線程和隊列模塊並行執行此操作(5名工作人員)。
它的偉大工程的查詢部分,因爲我可以提交多個搜索工作和處理結果,因爲他們進來。
但是,看來我的所有線程都綁定到同一核心。當它到達處理XML的部分時(這是cpu密集型),這是顯而易見的。

有其他人遇到過這個問題嗎?我在概念上錯過了什麼?

而且,我在思考有兩個獨立的工作隊列,一個是爲了使查詢和一個用於解析XML的想法。就像現在一樣,一名工作人員將連續進行這兩項工作。如果有的話,我不確定那會買什麼。任何幫助是極大的讚賞。

下面是代碼:(除去專有數據)

def addWork(source_list): 
    for item in source_list: 
     #print "adding: '%s'"%(item) 
     work_queue.put(item) 

def doWork(thread_id): 
    while 1: 
     try: 
      gw = work_queue.get(block=False) 
     except Queue.Empty: 
      #print "thread '%d' is terminating..."%(thread_id) 
      sys.exit() # no more work in the queue for this thread, die quietly 

    ##Here is where i make the call to the REST API 
    ##Here is were i wait for the results 
    ##Here is where i parse the XML results and dump the data into a "global" dict 

#MAIN 
producer_thread = Thread(target=addWork, args=(sources,)) 
producer_thread.start() # start the thread (ie call the target/function) 
producer_thread.join() # wait for thread/target function to terminate(block) 

#start the consumers 
for i in range(5): 
    consumer_thread = Thread(target=doWork, args=(i,)) 
    consumer_thread.start() 
    thread_list.append(consumer_thread) 

for thread in thread_list: 
    thread.join() 

回答

4

這是CPython的如何處理線程的副產物。圍繞互聯網進行了無盡的討論(搜索GIL),但解決方案是使用multiprocessing模塊而不是threadingMultiprocessing與接口(和同步結構,所以你仍然可以使用隊列)的線程幾乎相同。它只是讓每個線程都擁有自己的整個進程,從而避免了GIL和強制串行化並行工作負載。

+0

儘管如此,你還是得圍繞你的信息。儘管模塊具有相同的接口,但不要假設發生同樣的情況 - 例如,在線程安全隊列中排隊和出隊不涉及將數據從進程複製到另一個進程。我會用完字符,請參閱下面的答案。 – slezica 2010-10-13 14:24:26

+0

工作!非常感謝你的幫助。 – nnachefski 2010-10-13 14:41:34

+0

這將解釋GIL相當不錯:http://blip.tv/file/2232410 – mix 2010-11-09 07:43:47

2

使用CPython的,你的線程將永遠不會真正並行的兩個不同的內核上運行。查找有關全球解釋器鎖(GIL)的信息。

基本上,有一個互斥鎖保護解釋的實際執行部分,所以沒有兩個線程可以並行計算。因爲阻塞,對於I/O任務的線程工作會很好。

編輯:如果你想充分利用多核心,你需要使用多個進程。有很多關於這個話題的文章,我正在努力爲你找到一個我記得很棒但找不到它= /。

由於納通建議,可以使用多道處理模塊。有些工具可以幫助您在進程之間共享對象(請參閱POSH,Python對象共享)。