Home  >  Article  >  Backend Development  >  How to implement multithreading in python

How to implement multithreading in python

高洛峰
高洛峰Original
2017-03-02 16:13:221432browse

Currently python provides several multi-threading implementation methods thread, threading, and multithreading. The thread module is relatively low-level, and the threading module provides some packaging for thread, which can be used more conveniently.

Before version 2.7, python’s support for threads was not complete enough and could not take advantage of multi-core CPUs. However, version 2.7 of python has considered improving this point, and the multithreading module has appeared. The threading module mainly objectifies some thread operations and creates Thread classes. Generally speaking, there are two modes for using threads:

A Create a function to be executed by the thread, pass this function into the Thread object, and let it execute;
B Inheritance Thread class, create a new class and write the code to be executed into the run function.

This article introduces two implementation methods.
The first method is to create a function and pass it into the Thread object
t.py script content

import threading,time
from time import sleep, ctime
def now() :
  return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
  print 'start loop', nloop, 'at:', now()
sleep(nsec)
  print 'loop', nloop, 'done at:', now()
def main():
  print 'starting at:',now()
  threadpool=[]
for i in xrange(10):
    th = threading.Thread(target= test,args= (i,2))
    threadpool.append(th)
for th in threadpool:
    th.start()
for th in threadpool :
    threading.Thread.join( th )
  print 'all Done at:', now()
if __name__ == '__main__':
    main()

thclass.py script content:

import threading ,time
from time import sleep, ctime
def now() :
  return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
class myThread (threading.Thread) :
"""docstring for myThread"""
   def __init__(self, nloop, nsec) :
     super(myThread, self).__init__()
     self.nloop = nloop
     self.nsec = nsec
   def run(self):
     print 'start loop', self.nloop, 'at:', ctime()
sleep(self.nsec)
     print 'loop', self.nloop, 'done at:', ctime()
def main():
   thpool=[]
   print 'starting at:',now()
for i in xrange(10):
     thpool.append(myThread(i,2))
for th in thpool:
     th.start()
for th in thpool:
     th.join()
   print 'all Done at:', now()
if __name__ == '__main__':
    main()

Is the above the entire content of this article? I hope it will be helpful to you. It will be helpful for everyone to learn python programming.

For more articles related to how python implements multi-threading, please pay attention to 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