One: Gil Global interpreter Lock Introduction
InCPython, the Global interpreter lock(OrGIL)python byte code. This lock is required, cpython memory management is not thread-safe. ( However, due to gil< Span style= "color: #008080; The existence of Font-weight:bold ", Other features have become dependent on the guarantees that it performs. ) /span>
1.What isGILGlobal interpreter Lock
GILThe essence is a mutual exclusion lock,Equivalent to execute permissions,There will be one in every process.GIL,Multiple threads within the same processHave to grabGILBefore you can useCpythonInterpreter to execute its own code,That is, multiple threads under the same process cannot implement parallelBut concurrency can be achievedInCpythonInterpreter under, If you want to implement parallel, you can turn on multiple processes
2. why gil
because Cpython garbage collection mechanism of the interpreter is not thread-safe
3. gil
gil, What should I do with concurrency
fromThreadingImportThreadImport TimedefTask (name):Print('%s is running'%name) Time.sleep (2)if __name__=='__main__': T1=thread (target=task,args= ('Thread 1',)) T2=thread (target=task,args= ('Thread 1',)) T3=thread (target=task,args= ('Thread 1',)) T1.start () T2.start () T3.start ( )
View Code
Two: Multithreading performance test
fromMultiprocessingImportProcess fromThreadingImportThreadImportOs,timedefWork (): Res=0 forIinchRange (100000000): Res*=Iif __name__=='__main__': L=[] Print(Os.cpu_count ()) Start=time.time () forIinchRange (6): #p=process (target=work)P=thread (target=Work ) L.append (P) p.start () forPinchl:p.join () Stop=time.time ()Print('run time is%s'% (Stop-start))#4.271663427352905
computationally Intensive: Multiple processes should be used
fromMultiprocessingImportProcess fromThreadingImportThreadImportThreadingImportOS, timedefWork (): Time.sleep (2)if __name__=='__main__': L=[] Start=time.time () forIinchRange (300): #p=process (target=work) #2.225289821624756p = Thread (target=work)#2.002105951309204l.append (P) p.start () forPinchl:p.join () Stop=time.time ()Print('run time is%s'% (Stop-start))
IO-intensive: Multithreading should be turned on
Python-Gil Global interpreter lock