Python Multi-Threading Examples in Detail
(A) Threading Basics
1. Create the thread:
The thread module provides the start_new_thread function to create a thread. start_new_thread allows you to manipulate the thread after it has been successfully created.
Its function prototype:
start_new_thread(function,atgs[,kwargs])
The meaning of the parameters is as follows:
function: the name of the function to be executed in the thread
args:List of arguments in tuple form.
kwargs: optional arguments, specified as dictionaries
Method 1: Create a new thread by using a function in the thread module.
>>> import thread >>> def run(n): for i in range(n): print i >>> thread.start_new_thread(run,(4,)) # Note that the second argument must be in the form of a tuple 53840 1 >>> 2 3 KeyboardInterrupt >>> thread.start_new_thread(run,(2,)) 17840 1 >>> thread.start_new_thread(run,(),{'n':4}) 39720 1 >>> 2 3 thread.start_new_thread(run,(),{'n':3}) 32480 1 >>> 2
Method 2: Creating threads through inheritance
>>> import threading >>> class mythread(): def __init__(self,num): .__init__(self) = num def run(self): # Overload the run method print 'I am', >>> t1 = mythread(1) >>> t2 = mythread(2) >>> t3 = mythread(3) >>> () # Run thread t1 I am >>> 1 () I am >>> 2 () I am >>> 3
Method 3: Use a function that runs directly in a thread.
import threading >>> def run(x,y): for i in range(x,y): print i >>> t1 = (target=run,args=(15,20)) # Directly use the Thread append function args as a function parameter. >>> () 15 >>> 16 17 18 19
ii) Common methods in Thread object:
1. isAlive method:
>>> import threading >>> import time >>> class mythread(): def __init__(self,id): .__init__(self) = id def run(self): (5) # Sleep for 5 seconds print >>> t = mythread(1) >>> def func(): () print () #Print thread status >>> func() True >>> 1
2. join method:
Prototype: join([timeout])
timeout: optional parameter, the maximum time for the thread to run
import threading >>> import time # Import the time module >>> class Mythread(): def __init__(self,id): .__init__(self) = id def run(self): x = 0 (20) print >>> def func(): () for i in range(5): print i >>> t = Mythread(2) >>> func() 0 1 2 3 4 >>> 2 def func(): () () for i in range(5): print i >>> t = Mythread(3) >>> func() 3 0 1 2 3 4 >>>
3. thread name:
>>> import threading >>> class mythread(): def __init__(self,threadname): .__init__(self,name=threadname) def run(self): print () >>> >>> t1 = mythread('t1') >>> () t1 >>>
4. setDaemon method
There is a main thread while the script is running, and if the main thread creates another sub-thread, then when the main thread exits, it will check if the sub-thread is complete. If the subthread is not completed, the main thread will wait for the subthread to complete before exiting.
When it is necessary for the main thread to exit with the main thread regardless of whether the child thread completes or not, then you can use the setDaemon method of the Thread object to set it.
(C) Thread synchronization
1. Simple thread synchronization
Simple thread synchronization can be achieved using the Lock and RLock of the Thread object. For data that needs to be manipulated by only one thread at a time, you can place the manipulation process between the acquire method and the release method. Such as:
# -*- coding:utf-8 -*- import threading import time class mythread(): def __init__(self,threadname): .__init__(self,name = threadname) def run(self): global x # Set global variables # () # Call the lock's acquire method for i in range(3): x = x + 1 (2) print x # () # Call the lock's release method #lock = () #Generate Rlock objects t1 = [] for i in range(10): t = mythread(str(i)) (t) x = 0 # Set the value of the global variable to 0 for i in t1: () E:/study/<a href="/base/python" rel="external nofollow" class='replace_word' title="Python Knowledge Base." target='_blank' style='color:#df3434; font-weight:bold;'>Python</a>/workspace> 3 6 9 12 15 18 21 24 27 30
If you save and run the script after removing () and (),lock = (), the result will be 10 outputs of 30. 30 is the final value of x. Since x is a global variable, each thread hibernates after operating on it, and while the threads are hibernating, the Python interpreter executes the other threads but the value of x increases. When all the threads have finished hibernating, the value of x has been changed to 30 by all the threads, so the output is all 30.
2. Use conditional variables to keep threads synchronized.
Python's Condition object provides support for synchronization of duplicate threads. Using the Condition object, data can be processed only after certain events are triggered.The Condition object has methods for require and release, as well as methods for wait, notify, and notifyAll for conditional processing.
# -*- coding:utf-8 -*- import threading class Producer(): def __init__(self,threadname): .__init__(self,name = threadname) def run(self): global x () if x == 1000000: () # pass else: for i in range(1000000): x = x + 1 () print x () class Consumer(): def __init__(self,threadname): .__init__(self,name = threadname) def run(self): global x () if x == 0: () #pass else: for i in range(1000000): x = x - 1 () print x () con = () x = 0 p = Producer('Producer') c = Consumer('Consumer') () () () () print x E:/study/python/workspace> 1000000 0 0
Inter-thread communication:
The Event object is used to communicate between threads. He provides a set of signals, clear the letter macro, wait for the implementation of inter-thread communication.
1. setSignal. isSet() method returns true after the Event object has used the set() method.
2. Clear the signal. The isSet() method returns false after using the clear() method of the Event object.
3. wait. When the internal signal flag of the Event object is false, the wait() method waits until it is true before returning. You can also pass a parameter to wait to set the maximum wait time.
# -*- coding:utf-8 -*- import threading class mythread(): def __init__(self,threadname): .__init__(self,name = threadname) def run(self): global event if (): () () # Returns when event is tagged print () else: print () () event = () () t1 = [] for i in range(10): t = mythread(str(i)) (t) for i in t1: ()
If you have any questions, please leave a message or to the site community exchange and discussion, thank you Read, I hope to help everyone, thank you for your support of this site!