If multiple threads modify a data together, unexpected results may occur. To ensure data correctness, multiple threads must be synchronized.
1. Simple thread synchronization.
The lock and rlock of the thread object can be used for simple thread synchronization. Both objects have the acquire and release methods. For data that requires only one thread to operate at a time, you can place the operations between the acquire and release methods. As follows:
Import threading
Import time
Class mythread (threading. Thread ):
Def _ init _ (self, threadname ):
Threading. thread. _ init _ (self, name = threadname)
Defrun (Self ):
Global x
Lock. Acquire ()
For I in range (3 ):
X = x + 1
Time. Sleep (2)
Print x
Lock. Release ()
Lock = threading. rlock ()
T1 = []
For I in range (10 ):
T = mythread (STR (I ))
T1.append (t)
X = 0
For I in T1:
I. Start ()
The running result is as follows:
>>> 3
6
9
12
15
18
21
24
27
30
>>>
If we remove acquire () and release (), the results will be different:
30303030303030303030
This is because every thread has to sleep for 2 seconds before printing X. In this process, every thread is executed, so wait until the sleep ends, the printed x value is naturally the X value after multiple operations.
For the first time, we place the global variable X Between acquire () and release (). The Python interpreter only allows one thread to operate X at a time, the next thread can operate on X only after the thread ends and the sleep ends and prints it out. Therefore, the output x increases progressively and takes a long time.
2. Use conditional variables to keep the thread synchronized
Python's condition object provides support for complex thread synchronization. It can be used to process data only after some events are triggered. There are many condition methods, as shown in the following example:
Use Condition to realize the relationship between famous producers and consumers:
Import threading
Class producer (threading. Thread ):
Def _ init _ (self, threadname ):
Threading. thread. _ init _ (self, name = threadname)
Defrun (Self ):
Global x
Con. Acquire ()
If X = 1000000:
Con. Wait ()
Pass
Else:
For I in range (1000000 ):
X = x + 1
Con. Sort y ()
Print x
Con. Release ()
Class consumer (threading. Thread ):
Def _ init _ (self, threadname ):
Threading. thread. _ init _ (self, name = threadname)
Defrun (Self ):
Global x
Con. Acquire ()
If X = 0:
Con. Wait ()
Pass
Else:
For I in range (1000000 ):
X = X-1
Con. Sort y ()
Print x
Con. Release ()
Con = threading. condition ()
X = 0
P = producer ('producer ')
C = Consumer ('consumer ')
P. Start ()
C. Start ()
P. Join ()
C. Join ()
Print x
The result is as follows:
>>>
1000000
0
0
>>>
3. Use a queue to maintain Thread Synchronization
In the same example, the queue can be used to implement a multi-producer and multi-consumer first-in-first-out queue. Each producer stores data in the queue in sequence, and each consumer extracts data from the queue in sequence, see the following example:
Import threading
Import time
Import queue
Class producer (threading. Thread ):
Def _ init _ (self, threadname ):
Threading. thread. _ init _ (self, name = threadname)
Defrun (Self ):
Global queue
Queue. Put (self. getname ())
Print self. getname (), 'put', self. getname (), 'to queue'
Class consumer (threading. Thread ):
Def _ init _ (self, threadname ):
Threading. thread. _ init _ (self, name = threadname)
Defrun (Self ):
Global queue
Print self. getname (), 'get', self. getname (), 'From queue'
Queue = queue. Queue ()
Plist = []
Clist = []
For I in range (10 ):
P = producer ('producer '+ STR (I ))
Plist. append (P)
For I in range (10 ):
C = Consumer ('consumer '+ STR (I ))
Clist. append (c)
For I in plist:
I. Start ()
I. Join ()
For I in clist:
I. Start ()
I. Join ()
Result:
>>>
Producer0 put producer0 to queue
Producer1 put producer1 to queue
Producer2 put producer2 to queue
Producer3 put producer3 to queue
Producer4 put producer4 to queue
Producer5 put producer5 to queue
Producer6 put producer6 to queue
Producer7 put producer7 to queue
Producer8 put producer8 to queue
Producer9 put producer9 to queue
Consumer0 get consumer0 from queue
Consumer1 get consumer1 from queue
Consumer2 get consumer2 from queue
Consumer3 get consumer3 from queue
Consumer4 get consumer4 from queue
Consumer5 get consumer5 from queue
Consumer6 get consumer6 from queue
Consumer7 get consumer7 from queue
Consumer8 get consumer8 from queue
Consumer9 get consumer9 from queue