Python multi-thread programming 3: Use mutex lock synchronization thread

Source: Internet
Author: User
In the above example, each thread is independent of each other and has no relationship with each other. Now let's assume that there is a global count num, and each thread gets this global...

In the preceding example, each thread is independent of each other and has no relationship with each other. Now let's assume that there is a global count num. each thread obtains the global count, processes it according to num, and adds num to 1. It is easy to write such code:

# encoding: UTF-8import threadingimport time  class MyThread(threading.Thread):    def run(self):        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__':    test()

However, the running result is incorrect:


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 cause of the problem is that the access to the same resource by multiple threads is not controlled, and the data is damaged, which makes the running result of the thread unpredictable. This phenomenon is called "thread unsafe ".

Mutex lock synchronization

The above example introduces the most common problem of multi-threaded programming: data sharing. When multiple threads modify a shared data, synchronous control is required.

Thread synchronization ensures secure access to competing resources by multiple threads. the simplest synchronization mechanism is to introduce mutex locks. The mutex lock introduces a status for the resource: locked/unlocked. When a thread wants to change the shared data, it first locks it. at this time, the resource status is "locked" and other threads cannot be changed until the thread releases resources, changes the resource status to "unlocked", and other threads can lock the resource again. The mutex lock ensures that only one thread writes data at a time, thus ensuring data correctness in the case of multiple threads.

The threading module defines the Lock class to facilitate Lock handling:

# Create a lock

Mutex = threading. Lock ()

# Locking

Mutex. acquire ([timeout])

# Release

Mutex. release ()

The locking method acquire can have an optional timeout parameter timeout. If timeout is set, you can use the returned value to determine whether the lock is obtained after the timeout, so that you can perform other processing.

The code for using mutex to implement the above example 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()

Running 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 the mutex lock is added, the running results are consistent with expectations.

Synchronization blocking

When a thread calls the lock's acquire () method to obtain the lock, the lock enters the "locked" state. Only one thread can obtain the lock at a time. If another thread tries to obtain the lock at this time, the thread changes to the "blocked" state, known as "synchronization blocking" (see the basic concept of multithreading ).

The lock enters the "unlocked" state after the locks are released by the release () method called by the thread that owns the lock. The thread scheduler selects one of the threads in the synchronous blocking state to obtain the lock and enters the running state.

The most basic content of mutex is this. the next section will discuss the RLock and deadlock issues.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.