Python provides support for multithreading through two standard libraries (thread, threading)
Thread module
Import TimeImportThreaddefRunner (ARG): forIinchRange (6): PrintSTR (i) +':'+Arg time.sleep (1) #End Current ThreadThread.exit_thread ()#equivalent to Thread.exit () #start a thread, the first argument is the function name,#The second parameter is a tuple type, which is a parameter passed to the functionThread.start_new_thread (Runner, ('Hello World',))#equivalent to Thread.start_new (runner, (' Hello World ')) #creates a lock, which is used for thread synchronization, and typically controls access to shared resourcesLock = Thread.allocate_lock ()#equivalent to Thread.allocate ()num =0#get lock, return true successfully, fail return falseiflock.acquire (): Num+ = 1#Release Locklock.release ()#threads that are provided by the thread module will end at the end of the main thread and therefore end the main thread delayTime.sleep (10) Print 'Num:'+STR (num)
threading.Thread
Common methods of Class
1. Called in its own thread class __ init__
, the threading.Thread.__init__(self,name=threadname)
name of the threadname
thread.
2. run()
it is often necessary to rewrite and write code to implement the required functionality.
3. getName()
, get the thread object name.
4. setName()
set the thread object name.
5. start()
, start the thread.
6. join([timeout])
wait for another thread to finish before running.
7. setDaemon(bool)
set whether the child thread ends with the main thread and must be start()
called before. The default is False.
8. isDaemon()
, determine whether the thread ends with the main threads.
9. isAlive()
Check that the thread is running.
To create a thread object, simply inherit the class and threading.Thread
then invoke the __ init__
method inside threading.Thread.__init__()
. Override the Run () method and put the functionality you want to implement in this method.
classRunner (threading. Thread):def __init__(self, name): Threading. Thread.__init__(self) self.name=name Self.thread_stop=FalsedefRun (self): while notSelf.thread_stop:PrintSTR (self.name) +':'+'Hello World'Time.sleep (1) defStop (self): Self.thread_stop=TruedefTest (): t= Runner ('Thread') T.start () Time.sleep (10) t.stop ()if __name__=='__main__': Test ()
Thread Synchronization (Lock)
The simplest synchronization mechanism is the lock. The lock object is created by the threading.RLock
class. A thread can use the lock method to obtain a lock so that the acquire()
lock enters the locked
state. Only one thread can get a lock at a time. If another thread attempts to acquire the lock, it will be turned into a state until the locked thread invokes the lock to blocked
release the lock release()
, and the lock enters the unlocked
state. blocked
the thread of the State receives a notification and has the right to obtain the lock.
If more than one thread is in blocked
the state, all threads are released first blocked
, and then the system chooses one thread to get the lock, and the other threads continue blocked
. Python threading module
is based on a built thread module
-in one module
, in thread module
which Python provides a user-level thread synchronization tool for the lock object.
In the threading module
middle, Python also provides a Lock
variant of the object: the RLock
object. RLock
An object is maintained inside an object Lock
, which is a Reentrant object. For a lock object, if a thread is operating two times in a row acquire
, the acquire
release
acquire
thread will be suspended the second time because there is no after the first time. This causes the Lock
object to never be release
, causing the thread to deadlock.
RLock
Object allows a thread to manipulate it more than once acquire
because the counter
number of threads is maintained internally through a variable acquire
. And each operation acquire
must have an release
action corresponding to it, after all the release
operations are completed, the other thread can request the RLock
object.
We refer to the code that modifies the shared data as a critical section. All critical sections must be enclosed in and between the same lock object acquire
release
.
Import TimeImportThreading Num=0 Lock=Threading. Rlock ()classRunner (threading. Thread):def __init__(self, name): Threading. Thread.__init__(self) self.name=namedefRun (self):GlobalNum whileTrue:ifNum >= 6: Break ifLock.acquire ():Print "Thread (%s) locked, number:%d"%(Self.name, num) time.sleep (1) lock.release ()Print "Thread (%s) released, Number:%d"%(Self.name, num) time.sleep (1) Num+ = 1defTest (): T1= Runner ('Thread1') T2= Runner ('thread2') T1.start () T2.start ()if __name__=='__main__': Test ()
Python Thread implements Multithreading
#-*-encoding:gb2312-*-Importstring, threading, timedefThread_main (a):Globalcount, Mutex#get the thread nameThreadName =Threading.currentthread (). GetName () forXinchxrange (0, Int (a)):#Get lockMutex.acquire () Count= Count + 1#Release Lockmutex.release ()PrintThreadName, X, Count Time.sleep (1) defMain (num):Globalcount, Mutex threads=[] Count= 1#Create a lockMutex =Threading. Lock ()#Create a Thread object first forXinchxrange (0, num): Threads.append (Threading. Thread (Target=thread_main, args= (10,))) #Start All Threads forTinchThreads:t.start ()#waiting for all child threads to exit in the main thread forTinchThreads:t.join ()if __name__=='__main__': Num= 4#Create 4 ThreadsMain (4)
Python Threading Implements Multithreading
#-*-encoding:gb2312-*-ImportThreadingImport TimeclassTest (Threading. Thread):def __init__(self, num): Threading. Thread.__init__(self) self._run_num=NumdefRun (self):Globalcount, Mutex ThreadName=Threading.currentthread (). GetName () forXinchxrange (0, int (self._run_num)): Mutex.acquire () Count= Count + 1mutex.release ()PrintThreadName, X, Count Time.sleep (1) if __name__=='__main__': Globalcount, Mutex threads=[] Num= 4Count= 1#Create a lockMutex =Threading. Lock ()#To create a thread object forXinchxrange (0, num): Threads.append (Test (10)) #Start Thread forTinchThreads:t.start ()#wait for the child thread to end forTinchThreads:t.join ()
[Python] Multithreading module thread and threading