【问题标题】:python3 appropriate way to interrupt multi-threadpython3中断多线程的适当方式
【发布时间】:2018-02-19 22:40:20
【问题描述】:

我在写一个多线程的网络爬虫,每个线程的例程函数基本上是一个死循环,并且有一个共享字典来存储那些已经访问过的url,我使用线程锁来同步.

有时我可能想用 ctrl+c 中断它,我在线程运行函数中添加一个 try catch 来捕捉键盘中断,然后我可能想做一些最终任务,例如将数据转储到数据库或 pkl 文件。

问题是每次我打断它,就是进不去catch进程,有时卡在那儿,有时还继续运行。

那么在多线程编程中处理异常/中断的最佳实践是什么?

我的代码如下:

from bs4 import BeautifulSoup
import requests
import threading
import queue
import pickle
import os
from concurrent.futures import ThreadPoolExecutor

worker_num = 8
q = queue.Queue()
lock = threading.Lock()

if os.path.exists('./checked.pkl'):
    with open('./checked.pkl', 'rb') as f:
        checked = pickle.load(f)
else:
    checked = set()


def get_links(url):
    # do sth....


def run():
    print(threading.current_thread())
    try:
        while True:
            next_url = q.get()
            links = get_links(next_url)
            lock.acquire()
            for link in links:
                if link not in checked:
                    q.put(link)
            print(len(checked))
            lock.release()
    except Exception as e:
        print(e)
        print('interrupt')
        lock.acquire()
        with open('./checked.pkl', 'wb') as f:
            pickle.dump(checked, f)
        lock.release()


if __name__ == '__main__':
    q.put(start_url)
    with ThreadPoolExecutor(worker_num) as executor:
        for _ in range(worker_num):
            executor.submit(run)

【问题讨论】:

    标签: python multithreading python-3.x


    【解决方案1】:

    KeyboardInterrupt 总是在主线程中引发。你不能在另一个线程中处理它。

    您应该在每个成功的工作块之后检查您的状态(不必在每个 URL 之后,但也可以)。即使您的进程由于其他原因(某些无法处理的原因 - 例如段错误或整个主机崩溃)而崩溃,这也会为您提供状态更新。您还应该以原子方式编写检查点,这样如果您在更新过程中崩溃,您就不会以损坏、不可用的状态告终。 (由于它的不安全性、脆弱性和跨语言挑战,您也不应该使用 pickle 作为您的检查点状态格式。)

    一旦在正常操作期间安全且定期地写入状态更新,您可以通过将工作线程设置为守护线程并将KeyboardInterrupt 处理添加到主线程来使爬虫可中断。此时,如果工作线程在没有机会进行清理的情况下被杀死(如果你让它们成为守护线程并让主线程退出,就会发生这种情况),因为它们最近会检查它们的状态。

    此外,您应该考虑使用现有的抓取工具,例如 Scrapy,而不是自己滚动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      相关资源
      最近更新 更多