Python multi-thread operations

Source: Internet
Author: User
Document directory
  • Mutex lock Synchronization

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 timeclass 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 () # Lock 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 timeclass 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.

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.