Home  >  Article  >  Backend Development  >  Detailed explanation of using Python multi-threading examples

Detailed explanation of using Python multi-threading examples

高洛峰
高洛峰Original
2017-03-28 09:43:081423browse

This article mainly introduces the relevant information of Python Detailed explanation of multi-threaded instances. Friends in need can refer to

Detailed explanation of Python multi-threaded instances

Multi-threading usually involves opening a new background thread to handle time-consuming operations. It is also very simple for Python to do background thread processing. Today I found a Demo from the official documentation.

Example code:

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.')

Result:

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 it can help everyone, thank you for your support of this site!

The above is the detailed content of Detailed explanation of using Python multi-threading examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn