Python currently offers several multi-threaded implementations, where the thread module is thread,threading,multithreading, while the threading module is a wrapper for thread and can be used more conveniently.
Prior to version 2.7, Python support for threads was not perfect enough to take advantage of multi-core CPUs, but the 2.7 version of Python has already been considered for improvement and there are multithreading modules. In the threading module, the main object of some threads is to create thread class. In general, there are two modes of using threads:
A creates a function to be executed by the thread, passing the function into the thread object and letting it execute;
B inherits the thread class, creates a new class, and writes the code to be executed into the run function.
This article introduces two implementation methods.
The first type creates a function and passes in the thread object
t.py Script Content
The code is as follows |
Copy Code |
Import threading, Time From time to 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 in: ', 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 in: ', now () if __name__ = = ' __main__ ': Main () |
Execution results:
thclass.py Script content:
code is as follows |
copy code |
Import threading, Time From time to 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 in: ', now () if __name__ = = ' __main__ ': Main ()
|
Execution results: