If multiple threads are working together on a data modification, unpredictable results may occur, and in order to ensure the correctness of the data, it is necessary to
synchronization of multiple threads。
Using the thread object's lock and Rlock allows for simple thread synchronization , both of which have the acquire method and the release method, for those data that require only one thread at a time, You can put its actions between the acquire and the release methods. As follows:
The advantage of multithreading is that you can run multiple tasks at the same time (at least it feels like this). However, when a thread needs to share data, there may be an issue with data that is out of sync.
Consider a situation in which all elements in a list are 0, the thread "set" changes all elements to 1 from the back, and the thread "print" is responsible for reading the list and printing from the front.
Then, when the thread "set" starts to change, the thread "print" will print the list, and the output will be half 01 and a half 1, which is a different step in the data. In order to avoid this situation, the concept of lock is introduced.
The lock has two states-locked and unlocked. Each time a thread such as "set" is to access the shared data, the lock must first be acquired, and if another thread such as "print" is locked, then the thread "set" is paused, that is, the synchronization is blocked, and the thread "set" continues after the thread "print" has been accessed, releasing the lock.
After this processing, the print list will either output 0, or all output 1, no more than half 1 and a half 1 embarrassing scenes.
#!/usr/bin/python#-*-coding:utf-8-*-import threadingimport timeclass myThread (Threading. Thread):d EF __init__ (self, ThreadID, name, counter): Threading. Thread.__init__ (self) self.threadid = Threadidself.name = Nameself.counter = Counterdef run (self):p rint ' starting ' + self . name# gets the lock and returns true# when the optional timeout parameter is not filled will block until the lock is obtained # otherwise the timeout will return Falsethreadlock.acquire () print_time (Self.name, Self.counter, 3) # Release lock Threadlock.release () def print_time (threadname, Delay, counter): while Counter:time.sleep (delay) Print "%s:%s"% (ThreadName, Time.ctime (Time.time ())) counter-= 1threadLock = Threading. Lock () threads = []# Create new Thread thread1 = MyThread (1, "Thread-1", 1) thread2 = MyThread (2, "Thread-2", 2) # Open new Thread Thread1.start () thr Ead2.start () # Add thread to Thread list threads.append (thread1) Threads.append (thread2) # Wait for all threads to finish for T in Threads:t.join () print " Exiting Main Thread "