Python multithreaded Programming 4: Deadlocks and reentrant locks

Source: Internet
Author: User
Dead lock

When multiple resources are shared between threads, a deadlock can occur if the two thread holds a portion of the resources and waits for each other's resources at the same time. Although deadlocks rarely occur, they can cause the application to stop responding when they occur. Let's look at a deadlock example:

# encoding:utf-8import Threadingimport Time Class MyThread (threading.             Thread): Def do1 (self): global ResA, Resb if Mutexa.acquire (): msg = self.name+ ' Got ResA '                 Print msg if Mutexb.acquire (1): msg = self.name+ ' Got Resb '        Print msg mutexb.release () mutexa.release () def do2 (self): global ResA, RESB If Mutexb.acquire (): msg = self.name+ ' Got resb ' Print msg if mu             Texa.acquire (1): msg = self.name+ ' Got ResA ' Print msg mutexa.release () Mutexb.release () def run (self): Self.do1 () self.do2 () ResA = 0resB = 0 Mutexa = thread Ing. Lock () Mutexb = Threading.  Lock () def test (): For I in range (5): T = MyThread () t.start () if __name__ = = ' __main__ ': Test () 

Execution Result:


Thread-1 got ResA

Thread-1 got Resb

Thread-1 got Resb

Thread-1 got ResA

Thread-2 got ResA

Thread-2 got Resb

Thread-2 got Resb

Thread-2 got ResA

Thread-3 got ResA

Thread-3 got Resb

Thread-3 got Resb

Thread-3 got ResA

Thread-5 got ResA

Thread-5 got Resb

Thread-5 got Resb

Thread-4 got ResA


At this point the process is dead.


Can be re-entered lock

A simpler deadlock scenario is a thread that "iterates" over the same resource, directly causing a deadlock:

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.acquire ()            mutex.release ()            mutex.release () num = 0mutex = Threading. Lock () def test (): For    I in range (5):        t = MyThread ()        T.start () if __name__ = = ' __main__ ':    Test ()

To support multiple requests for the same resource in the same thread, Python provides a "reentrant lock": Threading. Rlock. Rlock internally maintains a lock and a counter variable, counter records the number of acquire, so that resources can be require multiple times. Until all the acquire of a thread are release, the other threads can get the resources. In the example above, if you use Rlock instead of lock, a deadlock will not occur:

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.acquire ()            mutex.release ()            mutex.release () num = 0mutex = Threading. Rlock () def test (): For    I in range (5):        t = MyThread ()        T.start () if __name__ = = ' __main__ ':    Test ()

Execution Result:


Thread-1 Set num to 1

Thread-3 Set num to 2

Thread-2 Set num to 3

Thread-5 Set num to 4

Thread-4 Set num to 5

  • 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.