gpt4 book ai didi

python 异步

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:36 25 4
gpt4 key购买 nike

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

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 异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7311710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com