gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:34:37 25 4
gpt4 key购买 nike

我正在编写一个应该多次获取 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 基本上在完成前一个线程后立即解释下一个线程?

谢谢。

最佳答案

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

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

然而,一般来说,multiprocessing当需要真正的并行性时,这是更安全的选择。

关于python - 同时在 python 中运行多个线程 - 这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7361922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com