我建议您阅读有关生产者-消费者问题的信息。生产者是获取线程。您的消费者就是
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



