Python multi-threaded usage scenario: IO operation, not suitable for CPU-intensive Operation task 1, multiple thread memory sharing 2, thread simultaneous modification of the same data need to lock, mutex mutex 3, recursive lock: Many locks, locks have lock 4, Python multi-threading, at the same time only the CPU is executing. To start a thread:
1 ImportThreading2 defrun (name)3 Print("run thread ....")4 5 #create Process object, target= method name, args= (parameter 1, parameter B,)6t = Threading. Thread (target=run,args=(n,))7 #Setting the daemon thread8 T.setdaemon (True)9 #Start ThreadTen T.start () One #wait for thread to end AT.jion ()
Model Quantity usage (thread pool)
1 ImportThreading2 Import Time3 4 defrun (n):5 #Locking6 Semaphore.acquire ()7 Print("look:%s"%N)8Time.sleep (0.5)9 #Release LockTen semaphore.release () One A if __name__=="__main__": - #allow 5 threads at a time -Semaphore = Threading. Boundedsemaphore (5) theTlist = [] - #How many threads are set - forIinchRange (33): -t = Threading. Thread (target=run,args=(i,)) + T.start () - tlist.append (t) + forRinchtlist: AR.jion ()
Python Multithreading knowledge-practical examples