Python Deadlock Prevention Method Instance Analysis

Source: Internet
Author: User

Python Deadlock Prevention Method Instance Analysis

This article describes how to avoid deadlocks in python. Share it with you for your reference. The specific analysis is as follows:

When two or more threads are waiting for resources, a deadlock occurs and the two threads wait for each other.

In this example, thread1 waits for thread2 to release the block, thread2 waits for thtead1 to release ablock,

The principle of avoiding deadlocks:

1. The lock must be obtained in a fixed order. In this column, the lock must be obtained first, and then block

2. The lock must be released in the order opposite to the lock obtained. Here, the block should be released first, and then the alock

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

Import threading, time

A = 5

Alock = threading. Lock ()

B = 5

Block = threading. Lock ()

Def thread1calc ():

Print "thread1 acquiring lock"

Alock. acquire ()

Time. sleep (5)

Print "thread1 acquiring lock B"

Block. acquire ()

A + = 5

B + = 5

Print "thread1 releasing both locks"

Block. release ()

Alock. release ()

Def thread2calc ():

Print "thread2 acquiring lock B"

Block. acquire ()

Time. sleep (5)

Print "thread2 acquiring lock"

Alock. acquire ()

Time. sleep (5)

A + = 10

B + = 10

Print "thread2 releasing both locks"

Block. release ()

Alock. release ()

T = threading. Thread (target = thread1calc)

T. setDaemon (1)

T. start ()

T = threading. Thread (target = thread2calc)

T. setDaemon (2)

T. start ()

While 1:

Time. sleep (300)

Output:

?

1

2

3

4

Thread1 acquiring lock

Thread2 acquiring lock B

Thread1 acquiring lock B

Thread2 acquiring lock

I hope this article will help you with Python programming.

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.