There is a Gil (Global interpreter Lock) in the CPython interpreter, regardless of how many threads, how many CPUs
His role is to ensure that only one thread can execute the code at the same time, which makes it impossible for us to parallelize when we use multithreading.
Because of the existence of a Gil, only one thread at a time can be executed by the CPU
Task: IO-intensive: Multithreading (multi-process + co-forming) can be used
Computationally intensive: Python is not applicable
(1) IO-intensive, CPU will be automatic switching to improve productivity
deflistenmusic (name):Print("beging listening to%s,%s"%(Name,time.ctime ())) Time.sleep (5) Print("End Listening%s"%time.ctime ())defRecordlog (name):Print("beging recoding to%s,%s"%(Name,time.ctime ())) Time.sleep (5) Print("End recoding%s"%time.ctime ())if __name__=='__main__': Threads=[] T1=threading. Thread (target=listenmusic,args= ("Phoenix legend",)) T2=threading. Thread (target=recordlog,args= ("python multithreading",)) Threads.append (t1) threads.append (T2) forTinchThreads:t.start ()
(2) compute-intensive CPUs are working, no IO-flow switching, multi-process not applicable
ImportThreading,timedefAdd (): S=0 forIinchRange (100000990): S+=IPrint("The cumulative result is:", s)defMul (): S1=1 forIinchRange (1,10000): S1*=IPrint("The result of the multiplicative is:", S1)if __name__=='__main__': Start=time.time () L=[] T1=threading. Thread (target=add) T2=threading. Thread (target=mul) L.append (t1) l.append (T2) forTinchL:t.start () forTinchL:t.join ()Print("Total time Spent", Time.time ()-start)
Python GIL: Global Interpreter