python可不可以同时执行1000个线程_同时在python中运行多个线程-有可能吗?

I'm writing a little crawler that should fetch a URL multiple times, I want all of the threads to run at the same time (simultaneously).

I've written a little piece of code that should do that.

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)

from the apache logs it doesn't seems like the threads are running simultaneously, there's a little gap between requests, it's almost undetectable but I can see that the threads are not really parallel.

I've read about GIL, is there a way to bypass it with out calling a C\C++ code?

I can't really understand how does threading is possible with GIL? python basically interpreters the next thread as soon as it finishes with the previous one?

Thanks.

解决方案

As you point out, the GIL often prevents Python threads from running in parallel.

However, that's not always the case. One exception is I/O-bound code. When a thread is waiting for an I/O request to complete, it would typically have released the GIL before entering the wait. This means that other threads can make progress in the meantime.

In general, however, multiprocessing is the safer bet when true parallelism is required.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值