The question is raised
In the example in the previous section, each thread is independent of each other and has no relationship to each other. Now suppose such an example: there is a global count num, each thread gets the global count, does some processing based on NUM, and then adds Num 1. It's easy to write code like this:
# Encoding:utf-8import Threadingimport Time class MyThread (threading. Thread): def run: Global num time.sleep (1) num = num+1 msg = self.name+ ' Set num to ' +str (num) Print Msgnum = 0def Test (): For I in range (5): t = MyThread () T.start () if __name__ = = ' __main__ ': te St ()
However, the result is not correct:
Thread-5 Set num to 2
Thread-3 Set num to 3
Thread-2 Set num to 5
Thread-1 Set num to 5
Thread-4 Set num to 4
The problem arises because there is no control over the access of multiple threads to the same resource, causing damage to the data and making the results of the thread run unpredictable. This behavior is called "Thread insecurity."
Mutual exclusion Lock Synchronization
The above example leads to the most common problem with multithreaded programming: Data sharing. Synchronization control is required when multiple threads modify a shared data.
Thread synchronization ensures that multiple threads secure access to competing resources, and the simplest synchronization mechanism is to introduce mutexes. A mutex introduces a state to a resource: locked/non-locked. When a thread changes the shared data, it locks it, the state of the resource is locked, the other thread cannot be changed, and until the thread frees the resource, the state of the resource becomes "non-locked", and the other thread can lock the resource again. The mutex ensures that only one thread is written at a time, thus guaranteeing the correctness of the data in multi-threaded situations.
The lock class is defined in the threading module, allowing for easy handling of locks:
#创建锁
Mutex = Threading. Lock ()
#锁定
Mutex.acquire ([timeout])
#释放
Mutex.release ()
Where the lock method acquire can have a time-out optional parameter of timeout. If timeout is set, the return value after timeout can be used to determine if a lock has been obtained, allowing for some additional processing.
The code for implementing the above example using a mutex is as follows:
Import Threadingimport Time class MyThread (threading. Thread): def run (self): global num time.sleep (1) if Mutex.acquire (1): num = num+1 msg = self.name+ ' Set num to ' +str (num) print msg mutex.release () num = 0mutex = Threading. Lock () def test (): For I in range (5): t = MyThread () T.start () if __name__ = = ' __main__ ': Test ()
Operation Result:
Thread-3 Set num to 1
Thread-4 Set num to 2
Thread-5 Set num to 3
Thread-2 Set num to 4
Thread-1 Set num to 5
As you can see, after joining the mutex, the running result matches the expected.
Synchronous blocking
When a thread calls the lock's acquire () method to obtain the lock, the lock enters the "locked" state. Only one thread can get a lock at a time. If another thread attempts to acquire the lock at this point, the thread becomes a "blocked" state called "synchronous blocking" (see Basic concepts of multithreading).
The lock enters the "unlocked" state until the lock's release () method is called by the thread that owns the lock. The thread scheduler chooses one of the threads in the synchronous blocking state to obtain the lock and causes the thread to enter the running (running) state.
The basic content of mutexes is these, and the next section discusses the Reentrant lock (Rlock) and deadlock issues.