Python 多線(xiàn)程實(shí)例詳解
多線(xiàn)程通常是新開(kāi)一個(gè)后臺(tái)線(xiàn)程去處理比較耗時(shí)的操作,Python做后臺(tái)線(xiàn)程處理也是很簡(jiǎn)單的,今天從官方文檔中找到了一個(gè)Demo.
實(shí)例代碼:
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.')
結(jié)果:
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 . . .
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注