Python多線程相比其它語言實現起來要簡單一點。最近做的工作是使用多線程將多個文件上傳至新浪微盤。下面簡要總結一下Python的多線程知識。
一、Python多線程知識
二、Python多線程使用舉例
class UploadThreadHandler():
def __init__(self, list_widget, cloud_path, access_token, thread_num=5):
self.access_token = access_token
self.threads = []
count = list_widget.count()
self.m_queue = Queue.Queue(count)
if count == 0:
return
for i in range(count): # 初始化隊列
self.m_queue.put((list_widget.item(i), cloud_path, list_widget))
for i in range(thread_num): # 初始化線程池
self.threads.append(UploadThread(self.m_queue, self.access_token))
self.threads[i].setName("i")
self.threads[i].start()
def wait_complete(self):
self.m_queue.join()
2).線程類,線程類的代碼如下所示,在run方法中,while循環不斷從queue中取出列表信息,然後根據列表信息,來執行文件的上傳工作。若隊列已空,則get拋出異常,從而導致線程結束。其餘代碼,可忽略。class UploadThread(threading.Thread):
def __init__(self, queue, access_token):
"""path 是本地的路徑"""
threading.Thread.__init__(self)
self.m_queue = queue
self.access_token = access_token
self.client = client(self.access_token)
self.exitFlag = False
def run(self):
"""上傳文件"""
print "start upload thread"
while self.exitFlag is not True:
if self.m_queue.empty():
break
try:
item, cloud_path, list_widget = self.m_queue.get()
if (item.text() == QtCore.QString("成功上傳...".decode("utf-8"))):
continue
sha1 = Util.q_string2str(item.text())
sha1 = sha1[sha1.rindex("\\") + 1:]
result, is_success = self.client.files_put(cloud_path + sha1, item.text())
print result, is_success
if is_success:
params = {"name": sha1, "option": "fragmentation"}
url = ConfigUtil.read_ops("config.config", "server_address", "address") + \
ConfigUtil.read_ops("config.config", "sub_address", "upload_state")
netutil.sendPost(url, params)
result = JsonUtil.str2json(result)
if "error" in result.keys():
continue
print "成功上傳文件" + cloud_path + sha1
item.setText("成功上傳...".decode("utf-8"))
except Exception, e:
print Exception, e
break
finally:
self.m_queue.task_done()
print "upload thread end"
以上代碼測試了幾次暫時沒有發現什麼錯誤,可以利用多線程多連接向新浪微盤同時上傳多個文件,比較快的。若連接開多了則新浪微盤會拒絕連接的。