python There are several ways to implement multithreading , What are they ?
at present python Provides several multithreading implementations thread,threading,multithreading , among thread The module is low level , and threading The module is right thread Made some packaging , It can be used more conveniently .2.7 Before the release python Thread support Holding is not perfect , Can't use multi-core CPU, however 2.7 Version of python This has been considered for improvement , There is multithreading modular .threading The module mainly objectifies the operation of some threads , establish Thread Of class.
Generally speaking , There are two modes of using threads :
A Create the function to be executed by the thread , Pass this function into Thread In the object , Let it execute ; B Inherit Thread class , Create a new class, Code to be executed writes run In the function .
The first one is Create a function and pass in Thread In the object
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()
The second is to create a new class, Code to be executed writes run In the function .
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()