首頁 >後端開發 >Python教學 >關於Python中多執行緒的詳解

關於Python中多執行緒的詳解

Y2J
Y2J原創
2017-04-28 09:47:471681瀏覽

這篇文章主要介紹了Python 多線程實例詳解的相關資料,需要的朋友可以參考下

#Python 多線程實例詳解

多線程通常是新開一個後台執行緒去處理比較耗時的操作,Python做後台執行緒處理也是很簡單的,今天從官方文件中找到了一個Demo.

實例程式碼:

import threading, zipfile 
class AsyncZip(threading.Thread): 
  def __init__(self, infile, outfile): 
    threading.Thread.__init__(self) 
    self.infile = infile 
    self.outfile = outfile 
  def run(self): 
    f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) 
    f.write(self.infile) 
    f.close() 
    print('Finished background zip of:', self.infile) 
 
background = AsyncZip('mydata.txt', 'myarchive.zip') 
background.start() 
print('The main program continues to run in foreground.') 
 
background.join()  # Wait for the background task to finish 
print('Main program waited until background was done.')

結果:

The main program continues to run in foreground. 
Finished background zip of: mydata.txt 
Main program waited until background was done. 
Press any key to continue . . .

以上是關於Python中多執行緒的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn