同时在 python 中运行多个线程 - 这可能吗?

2023-12-30

我正在编写一个小爬虫,它应该多次获取 URL,我希望所有线程同时运行。

我写了一小段代码应该可以做到这一点。

import thread
from urllib2 import Request, urlopen, URLError, HTTPError


def getPAGE(FetchAddress):
    attempts = 0
    while attempts < 2:
        req = Request(FetchAddress, None)
        try:
            response = urlopen(req, timeout = 8) #fetching the url
            print "fetched url %s" % FetchAddress
        except HTTPError, e:
            print 'The server didn\'t do the request.'
            print 'Error code: ', str(e.code) + "  address: " + FetchAddress
            time.sleep(4)
            attempts += 1
        except URLError, e:
            print 'Failed to reach the server.'
            print 'Reason: ', str(e.reason) + "  address: " + FetchAddress
            time.sleep(4)
            attempts += 1
        except Exception, e:
            print 'Something bad happened in gatPAGE.'
            print 'Reason: ', str(e.reason) + "  address: " + FetchAddress
            time.sleep(4)
            attempts += 1
        else:
            try:
                return response.read()
            except:
                "there was an error with response.read()"
                return None
    return None

url = ("http://www.domain.com",)

for i in range(1,50):
    thread.start_new_thread(getPAGE, url)

从apache日志来看,线程似乎没有同时运行,请求之间有一点间隙,几乎无法检测到,但我可以看到线程并不是真正并行的。

我读过有关 GIL 的内容,有没有办法绕过它而不调用 C\C++ 代码? 我真的不明白 GIL 是如何实现线程化的? python 基本上在前一个线程完成后立即解释下一个线程?

Thanks.


正如您所指出的,GIL 通常会阻止 Python 线程并行运行。

然而,情况并非总是如此。一个例外是 I/O 密集型代码。当线程等待 I/O 请求完成时,它通常会在进入等待之前释放 GIL。这意味着其他线程可以同时取得进展。

然而,一般来说,multiprocessing http://docs.python.org/library/multiprocessing.html当需要真正的并行性时,这是更安全的选择。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

同时在 python 中运行多个线程 - 这可能吗? 的相关文章

随机推荐