This article mainly introduces two methods for implementing multi-threading in python. if you are interested, refer to the several multi-threaded implementation methods provided by python, such as thread, threading, and multithreading, among them, the thread module is relatively low-level, while the threading module is encapsulated for thread, which can be used more conveniently.
Python earlier than version 2.7 does not fully support threads and cannot use multi-core CPUs. However, python version 2.7 has already considered improvements, and the multithreading module has emerged. The threading module is mainly used to visualize some Thread operations and create the Thread class. Generally, there are two threads:
A creates the function to be executed by the Thread and passes the function into the Thread object for execution;
B inherits the Thread class, creates a new class, and writes the code to be executed to the run function.
This article introduces two implementation methods.
First, create a function and pass it into the Thread object.
T. py script content
import threading,timefrom time import sleep, ctimedef 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 ,timefrom time import sleep, ctimedef 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 all the content in this article, and I hope it will help you learn python programming.
For more articles on how to implement multiple threads in python, refer to PHP Chinese network!