想象一个20 mb的文本文件。我正在逐字符读取char并提取有用的信息。我实际上有2个主要功能,一个是读取文件,第二个是提取信息。像这样:

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


现在,我的目标是在提取器工作时继续阅读。所以从根本上讲,我的问题是实现目标的适当方法是什么?

最佳答案

您可以使用生产者/消费者线程。可以使用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)


如您所见,如果执行此命令,则将按正确的顺序使用所有内容。

关于python - python异步,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7311710/

10-12 18:36