2011-09-05 66 views
2

想象一下20 MB的文本文件。我正在通過字符讀取字符並提取有用的信息。實際上我有兩個主要功能,一個是讀取文件,另一個是提取信息。類似這樣的:python不同步

def reader(path): 
    f = open(path, 'r') 
    source = f.read() 
    f.close() 

    while True: 
     # here is where I read char by char and call the function extractor 

def extractor(s): 
    # here I extract the useful information 

現在,我的目標是在提取器工作時繼續閱讀。所以基本上,我的問題是什麼才能實現我的目標?

+0

哪個版本的Python?因爲在3.2+,我推薦concurrent.futures模塊。 – utdemir

+0

我正在使用Python 2.7 – Shaokan

+1

您是否確實看到性能問題而沒有併發讀取和處理?從現代硬盤讀取20MB應該只需幾秒鐘,因此獲得這個時間是潛在加速的絕對限制。 –

回答

3

您可以使用生產者/消費者線程。線程可以使用Queue.Queue進行同步。

編輯:生產者/消費者系統的一個例子:

from threading import Thread 
from Queue import Queue 


def produce(queue, n_items): 
    for d in range(n_items): 
     queue.put(d) 
     print "put {0} in queue".format(d) 

def consume(queue, n_items): 
    d = 0 
    while d != n_items -1: # You need some sort of stop condition 
     d = queue.get() 
     print "got {0} from queue".format(d) 

def start_producer_and_consumer(wait): 
    q = Queue() 
    consumer_thread = Thread(target = consume, args = (q, 10)) 
    producer_thread = Thread(target = produce, args = (q, 10)) 
    producer_thread.start() 
    consumer_thread.start() 
    if wait: 
     producer_thread.join() 
     consumer_thread.join() 

if __name__ == '__main__': 
    start_producer_and_consumer(True) 

至於如果執行此,你會看到,一切都會以正確的順序被消耗。

+0

我有線程問題。例如,如果我使用線程將1,2,3,4,5,6,7,8,9放入隊列中,我奇怪地收到一個結果,如1,3,4,5,2,6,8,7 ,9 – Shaokan

+0

編輯我的答案來解決這個問題。 – pvoosten