How to create a thread object:
The thread class is created directly
Import Threadingimport timedef countnum (n): # defines a function for a thread to run print ("Running on number:%s"%n) Time.sleep (3) if __ name__ = = ' __main__ ': t1 = Threading. Thread (target=countnum,args= ()) #生成一个线程实例 t2 = Threading. Thread (target=countnum,args=,)) T1.start () #启动线程 t2.start () print ("ending!")
Thread Class inheritance Creation
#继承Thread式创建import threadingimport timeclass MyThread (threading. Thread): def __init__ (self,num): Threading. Thread.__init__ (self) # with the parent class init self.num=num def run (self): print ("Running on number:%s"%self.num) Time.sleep (3) T1=mythread (56) # Thread Object T2=mythread (+) T1.start () # Activate Thread object T2.start () print ("Ending")
Thread Safety
Data corruption occurs when multiple threads are processing public data
Import Threadingimport Timedef sub (): Global num temp=num
Num=temp-1 time.sleep (2) num=100l=[]lock=threading. Lock () for I in range: t=threading. Thread (target=sub,args= ()) T.start () l.append (t) for T in L: t.join () print (num)
Multiple threads Rob Gil Lock, when in the sleep state thread, will not Rob Gil Lock, other threads in the time of the robbery, the previous will not wake up, each thread has a temp=100, when the first wake up, perform-1 operation, get 99 assigned to the global NUM, and then sleep , when the second thread wakes up, it also uses temp=100 minus 1, gets 99, and so on, and then assigns 99,100 times to NUM, and the result is 99.
If the thread wakes up before all threads are executed, the Gil Lock is taken, and the temp assignment is completed before the thread switches, so when sleep (0.1) is not performed, the result is 0.
Mutual exclusion Lock
A global lock that will serialize the code to ensure data security
Locks are often used to achieve synchronous access to shared resources. Create a lock object for each shared resource, and when you need to access the resource, call the Acquire method to get the lock object (if the other thread has already acquired the lock, the current thread waits for it to be freed), and then call the release method to release the lock when the resource has finished accessing it:
Import threadingr=threading. Lock () R.acquire () "operation on public Data" ' R.release ()
Import Threadingimport Timedef sub (): Global num lock.acquire () #获取锁 temp=num time.sleep (0.001 ) num=temp-1 lock.release () # release Lock # can only be occupied by one thread, and subsequent threads will wait for the lock to be released, only after the second thread can continue execution Time.sleep (2) Num=100l=[]lock = Threading. Lock () # Mutex object for I in range: t=threading. Thread (target=sub,args= ()) T.start () l.append (t) for T in L: t.join () print (num)
Deadlock:
Two or two or more processes or threads in the execution process, because of contention for resources caused by a mutual waiting phenomenon, if there is no external force, they will not be able to proceed. At this point the system is in a deadlock state or the system generates a deadlock, and these processes, which are always waiting on each other, are called deadlock processes.
import threadingimport timeclass MyThread (threading. Thread): def __init__ (self): threading. Thread.__init__ (self) # inherits the parent class Def run (self): Self.foo () Self.bar () def foo (self): Locka.acquire ( ) Print ("%s Locka%s"% (Self.name,time.ctime ())) Lockb.acquire () print ("%s lockb%s"% (self.name,time.c Time ())) Lockb.release () locka.release () def bar (self): Lockb.acquire () print ("%s lockb%s" % (Self.name, Time.ctime ())) Time.sleep (1) # When the SLEEP1 is here, the a lock has been taken by other threads, and there is no lock on it. Locka.acquire () Print ("%s Locka%s"% (Self.name, Time.ctime ())) Locka.release () lockb.release () locka=threading. Lock () lockb=threading. Lock () for I in Range: T=mythread () T.start () # Thread-1 Locka Sat Feb 15:41:34 2018# Thread-1 lockb Sa T 15:41:34 2018# Thread-1 lockb Sat Feb 15:41:34 2018# Thread-2 locka Sat Feb 15:41:34 2018
Recursive lock
In Python, in order to support multiple requests for the same resource in the same thread, Python provides a reentrant lock rlock. The Rlock internally maintains a lock and a counter variable, counter records the number of acquire, so that resources can be require multiple times. Until all the acquire of a thread are release, the other threads can get the resources. In the example above, if you use Rlock instead of lock, a deadlock will not occur:
Principle:
This lock allows multiple acquire and release, as long as the counter is greater than 0, other threads will not be eligible to grab the lock.
Import Threadingimport Timeclass MyThread (threading. Thread): def __init__ (self): threading. Thread.__init__ (self) # inherits the parent class def run (self): Self.foo () Self.bar () def foo (self): Rlock.acquire () # count 1 print ("%s Locka%s"% (Self.name,time.ctime ())) Rlock.acquire () # 2 print ("%s lockb%s"% ( Self.name,time.ctime ())) rlock.release () rlock.release () # count 0 def bar (self): Rlock.acquire () print ("%s lockb%s"% (Self.name, Time.ctime ())) Time.sleep (1) # When this sleep1, a lock has been taken by other threads, and there is no lock. rlock.acquire () print ("%s Locka%s"% (Self.name, Time.ctime ())) rlock.release () rlock.release () # locka=threading. Lock () # lockb=threading. Lock () Rlock = Threading. Rlock () for I in range: t=mythread () T.start ()
Signal Volume Semaphore
Semaphore manages a built-in counter,
Built-in counter whenever acquire () is called-1;
Built-in counter +1 when call Release ();
The counter cannot be less than 0, and when the counter is 0 o'clock, acquire () blocks the thread until another thread calls release ()
Function: How many processes are allowed to open simultaneously
Import Threadingimport Timesemaphore = Threading. Semaphore (5) # 5 threads at the same time, maximum number of connections 5 def func (): semaphore.acquire () time.sleep (2) print ("OK") Semaphore.release () for I in range: t=threading. Thread (target=func,args= ()) T.start ()
36. Thread and Lock