3

来自python 线程文档

在 CPython 中,由于全局解释器锁,只有一个线程可以一次执行 Python 代码(即使某些面向性能的库可能会克服这个限制)。如果您希望您的应用程序更好地利用多核机器的计算资源,建议您使用多处理。但是,如果您想同时运行多个 I/O 密集型任务,线程仍然是一个合适的模型。

现在我有一个像这样的线程工作者

def worker(queue):
    queue_full = True
    while queue_full:
        try:
            url = queue.get(False)
            w = Wappalyzer(url)
            w.analyze()
            queue.task_done()

        except Queue.Empty:
            queue_full = False

这里w.analyze()做两件事

  1. requests使用库抓取 url
  2. pyv8使用javascript 库分析抓取的 html

据我所知,1受 I/O 限制且2受 CPU 限制。

这是否意味着,申请了 GIL 2,我的程序将无法正常运行?

4

1 回答 1

4

The GIL description does not say anything about correctness, only about efficiency.

If 2 is CPU bound, you will not be able to get multicore performance out of threading, but your program will still perform correctly.

If you care about CPU Parallelism, you should use Python's multiprocessing library.

于 2014-05-09T21:40:43.757 回答