栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python线程安全的队列生产者-消费者

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python线程安全的队列生产者-消费者

我建议您阅读有关生产者-消费者问题的信息。生产者是获取线程。您的消费者就是

save
功能。如果我理解正确,您希望使用者尽快将获取的结果保存起来。为此,生产者和使用者必须能够以某种线程安全的方式(例如队列)进行通信。

基本上,您需要另一个队列。它将取代

proxy_array
。您的
save
函数将如下所示:

while True: try:   data = fetch_data_from_output_queue()   save_to_database(data) except EmptyQueue:   if not stop_flag.is_set():     # All done     break   time.sleep(1)   continue

save
函数将需要在其自己的线程中运行。
stop_flag
是一个事件, 您加入获取线程 会被设置。

从高层次看,您的应用程序将如下所示:

input_queue = initialize_input_queue()ouput_queue = initialize_output_queue()stop_flag = Event()create_and_start_save_thread(output_queue) # read from output queue, save to DBcreate_and_start_fetch_threads(input_queue, output_queue) # get sites to crawl from input queue, push crawled results to output_queuejoin_fetch_threads() # this will block until the fetch threads have gone through everything in the input_queuestop_flag.set() # this will inform the save thread that we are donejoin_save_thread() # wait for all the saving to complete


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/646839.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号