At present, Python provides several ways to implement multi-threading thread,threading,multithreading, where the thread module compared to the bottom, and the threading module is the thread to do some packaging, can be more convenient to be used.
Prior to version 2.7, Python's support for threading was not complete enough to take advantage of multicore CPUs, but the 2.7 version of Python had already considered improving this and the multithreading module appeared. The threading module is mainly about manipulating some threads, creating the class of thread. In general, there are two modes of using threads:
A Create a function to execute the thread, pass the function into the thread object, and let it execute;
B inherit the thread class, create a new class, and write the code that will be executed into the run function.
This article describes two methods of implementation.
The first creates a function and passes in 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 on: ', 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 do at: ', now ()
- if __name__ = = ' __main__ ':
- Main ()
Execution Result:
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 do at: ', now ()
- if __name__ = = ' __main__ ':
- Main ()
Execution Result:
"Python" python multithreading two ways to implement