【发布时间】:2013-04-18 13:32:27
【问题描述】:
我有以下问题。每当子线程想要执行一些 IO 操作(写入文件、下载文件)时,程序就会挂起。在以下示例中,程序挂起在opener.retrieve。如果我执行 python main.py 程序在检索功能上被阻止。如果我执行python ./src/tmp.py 一切都很好。我不明白为什么。谁能解释一下发生了什么?
我在Linux系统上使用python2.7(内核3.5.0-27)。
文件排序:
main.py
./src
__init__.py
tmp.py
main.py
import src.tmp
tmp.py
import threading
import urllib
class DownloaderThread(threading.Thread):
def __init__(self, pool_sema, i):
threading.Thread.__init__(self)
self.pool_sema = pool_sema
self.daemon = True
self.i = i
def run(self):
try:
opener = urllib.FancyURLopener({})
opener.retrieve("http://www.greenteapress.com/thinkpython/thinkCSpy.pdf", "/tmp/" + str(self.i) + ".pdf")
finally:
self.pool_sema.release()
class Downloader(object):
def __init__(self):
maxthreads = 1
self.pool_sema = threading.BoundedSemaphore(value=maxthreads)
def download_folder(self):
for i in xrange(20):
self.pool_sema.acquire()
print "Downloading", i
t = DownloaderThread(self.pool_sema,i)
t.start()
d = Downloader()
d.download_folder()
【问题讨论】:
标签: python multithreading python-2.7 io