Python multithreading example details
- 2020-05-27 06:11:28
Python multithreading example in detail
Multithreading usually involves opening a new background thread to handle time-consuming operations. It is also very easy for Python to handle background threads. Today, I found an Demo in the official document.
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 . . .
Thank you for reading, I hope to help you, thank you for your support of this site!