您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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 DB
create_and_start_fetch_threads(input_queue, output_queue) # get sites to crawl from input queue, push crawled results to output_queue
join_fetch_threads() # this will block until the fetch threads have gone through everything in the input_queue
stop_flag.set() # this will inform the save thread that we are done
join_save_thread() # wait for all the saving to complete
python 2022/1/1 18:33:17 有452人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶