Home Backend Development Python Tutorial Examples to explain the use of thread locks in Python programming

Examples to explain the use of thread locks in Python programming

Aug 04, 2016 am 08:55 AM
python thread Lock

Lock

Python's built-in data structures such as lists and dictionaries are thread-safe, but simple data types such as integers and floating-point numbers are not thread-safe. To operate these simple data types, you need to use locks.

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

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

#!/usr/bin/env python3

# coding=utf-8

 

import threading

 

shared_resource_with_lock = 0

shared_resource_with_no_lock = 0

COUNT = 100000

shared_resource_lock = threading.Lock()

 

####LOCK MANAGEMENT##

def increment_with_lock():

  global shared_resource_with_lock

  for i in range(COUNT):

    shared_resource_lock.acquire()

    shared_resource_with_lock += 1

    shared_resource_lock.release()

     

def decrement_with_lock():

  global shared_resource_with_lock

  for i in range(COUNT):

    shared_resource_lock.acquire()

    shared_resource_with_lock -= 1

    shared_resource_lock.release()

    ####NO LOCK MANAGEMENT ##

   

def increment_without_lock():

  global shared_resource_with_no_lock

  for i in range(COUNT):

    shared_resource_with_no_lock += 1

   

def decrement_without_lock():

  global shared_resource_with_no_lock

  for i in range(COUNT):

    shared_resource_with_no_lock -= 1

   

####the Main program

if __name__ == "__main__":

  t1 = threading.Thread(target = increment_with_lock)

  t2 = threading.Thread(target = decrement_with_lock)

  t3 = threading.Thread(target = increment_without_lock)

  t4 = threading.Thread(target = decrement_without_lock)

  t1.start()

  t2.start()

  t3.start()

  t4.start()

  t1.join()

  t2.join()

  t3.join()

  t4.join()

  print ("the value of shared variable with lock management is %s"\

  %shared_resource_with_lock)

  print ("the value of shared variable with race condition is %s"\

  %shared_resource_with_no_lock)

Copy after login

Execution result:

1

$ ./threading_lock.py

Copy after login

1

2

the value of shared variable with lock management is 0

the value of shared variable with race condition is 0

Copy after login

Another example:

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

37

38

39

40

41

42

import random

import threading

import time

logging.basicConfig(level=logging.DEBUG,

          format='(%(threadName)-10s) %(message)s',

          )

           

class Counter(object):

  def __init__(self, start=0):

    self.lock = threading.Lock()

    self.value = start

  def increment(self):

    logging.debug(time.ctime(time.time()))

    logging.debug('Waiting for lock')

    self.lock.acquire()

    try:

      pause = random.randint(1,3)

      logging.debug(time.ctime(time.time()))

      logging.debug('Acquired lock')     

      self.value = self.value + 1

      logging.debug('lock {0} seconds'.format(pause))

      time.sleep(pause)

    finally:

      self.lock.release()

def worker(c):

  for i in range(2):

    pause = random.randint(1,3)

    logging.debug(time.ctime(time.time()))

    logging.debug('Sleeping %0.02f', pause)

    time.sleep(pause)

    c.increment()

  logging.debug('Done')

counter = Counter()

for i in range(2):

  t = threading.Thread(target=worker, args=(counter,))

  t.start()

logging.debug('Waiting for worker threads')

main_thread = threading.currentThread()

for t in threading.enumerate():

  if t is not main_thread:

    t.join()

logging.debug('Counter: %d', counter.value)

Copy after login

Execution result:

1

$ python threading_lock.py

Copy after login

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

(Thread-1 ) Tue Sep 15 15:49:18 2015

(Thread-1 ) Sleeping 3.00

(Thread-2 ) Tue Sep 15 15:49:18 2015

(MainThread) Waiting for worker threads

(Thread-2 ) Sleeping 2.00

(Thread-2 ) Tue Sep 15 15:49:20 2015

(Thread-2 ) Waiting for lock

(Thread-2 ) Tue Sep 15 15:49:20 2015

(Thread-2 ) Acquired lock

(Thread-2 ) lock 2 seconds

(Thread-1 ) Tue Sep 15 15:49:21 2015

(Thread-1 ) Waiting for lock

(Thread-2 ) Tue Sep 15 15:49:22 2015

(Thread-1 ) Tue Sep 15 15:49:22 2015

(Thread-2 ) Sleeping 2.00

(Thread-1 ) Acquired lock

(Thread-1 ) lock 1 seconds

(Thread-1 ) Tue Sep 15 15:49:23 2015

(Thread-1 ) Sleeping 2.00

(Thread-2 ) Tue Sep 15 15:49:24 2015

(Thread-2 ) Waiting for lock

(Thread-2 ) Tue Sep 15 15:49:24 2015

(Thread-2 ) Acquired lock

(Thread-2 ) lock 1 seconds

(Thread-1 ) Tue Sep 15 15:49:25 2015

(Thread-1 ) Waiting for lock

(Thread-1 ) Tue Sep 15 15:49:25 2015

(Thread-1 ) Acquired lock

(Thread-1 ) lock 2 seconds

(Thread-2 ) Done

(Thread-1 ) Done

(MainThread) Counter: 4

Copy after login

Acquire() passes a False value to check whether the lock is acquired. For example:

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

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

import logging

import threading

import time

logging.basicConfig(level=logging.DEBUG,

          format='(%(threadName)-10s) %(message)s',

          )

           

def lock_holder(lock):

  logging.debug('Starting')

  while True:

    lock.acquire()

    try:

      logging.debug('Holding')

      time.sleep(0.5)

    finally:

      logging.debug('Not holding')

      lock.release()

    time.sleep(0.5)

  return

           

def worker(lock):

  logging.debug('Starting')

  num_tries = 0

  num_acquires = 0

  while num_acquires < 3:

    time.sleep(0.5)

    logging.debug('Trying to acquire')

    have_it = lock.acquire(0)

    try:

      num_tries += 1

      if have_it:

        logging.debug('Iteration %d: Acquired',

               num_tries)

        num_acquires += 1

      else:

        logging.debug('Iteration %d: Not acquired',

               num_tries)

    finally:

      if have_it:

        lock.release()

  logging.debug('Done after %d iterations', num_tries)

lock = threading.Lock()

holder = threading.Thread(target=lock_holder,

             args=(lock,),

             name='LockHolder')

holder.setDaemon(True)

holder.start()

worker = threading.Thread(target=worker,

             args=(lock,),

             name='Worker')

worker.start()

Copy after login

Execution result:

1

$ python threading_lock_noblock.py

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

(LockHolder) Starting

(LockHolder) Holding

(Worker  ) Starting

(LockHolder) Not holding

(Worker  ) Trying to acquire

(Worker  ) Iteration 1: Acquired

(LockHolder) Holding

(Worker  ) Trying to acquire

(Worker  ) Iteration 2: Not acquired

(LockHolder) Not holding

(Worker  ) Trying to acquire

(Worker  ) Iteration 3: Acquired

(LockHolder) Holding

(Worker  ) Trying to acquire

(Worker  ) Iteration 4: Not acquired

(LockHolder) Not holding

(Worker  ) Trying to acquire

(Worker  ) Iteration 5: Acquired

(Worker  ) Done after 5 iterations

Copy after login

Thread safe lock

1

threading.RLock()

Copy after login

Returns a reentrant lock object. A reentrant lock must be released by the thread that acquired it. Once a thread acquires a reentrant lock, the same thread can acquire it again without blocking, and must be released after acquisition.

Usually a thread can only acquire the lock once:

1

2

3

4

5

6

import threading

 

lock = threading.Lock()

 

print 'First try :', lock.acquire()

print 'Second try:', lock.acquire(0)

Copy after login

Execution result:

1

$ python threading_lock_reacquire.py

Copy after login

1

2

First try : True

Second try: False

Copy after login

Use RLock to obtain multiple locks:

1

2

3

4

import threading

lock = threading.RLock()

print 'First try :', lock.acquire()

print 'Second try:', lock.acquire(0)

Copy after login

Execution result:

1

python threading_rlock.py

Copy after login

1

2

First try : True

Second try: 1

Copy after login

Let’s look at another example:

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

37

38

39

40

41

42

43

44

45

46

47

48

49

50

#!/usr/bin/env python3

# coding=utf-8

import threading

import time

class Box(object):

  lock = threading.RLock()

  def __init__(self):

    self.total_items = 0

  def execute(self,n):

    Box.lock.acquire()

    self.total_items += n

    Box.lock.release()

  def add(self):

    Box.lock.acquire()

    self.execute(1)

    Box.lock.release()

  def remove(self):

    Box.lock.acquire()

    self.execute(-1)

    Box.lock.release()

     

## These two functions run n in separate

## threads and call the Box's methods   

def adder(box,items):

  while items > 0:

    print ("adding 1 item in the box\n")

    box.add()

    time.sleep(5)

    items -= 1

     

def remover(box,items):

  while items > 0:

    print ("removing 1 item in the box")

    box.remove()

    time.sleep(5)

    items -= 1

     

## the main program build some

## threads and make sure it works

if __name__ == "__main__":

  items = 5

  print ("putting %s items in the box " % items)

  box = Box()

  t1 = threading.Thread(target=adder,args=(box,items))

  t2 = threading.Thread(target=remover,args=(box,items))

  t1.start()

  t2.start()

  t1.join()

  t2.join()

  print ("%s items still remain in the box " % box.total_items)

Copy after login

Execution result:

1

$ python3 threading_rlock2.py

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

putting 5 items in the box

adding 1 item in the box

removing 1 item in the box

adding 1 item in the box

removing 1 item in the box

adding 1 item in the box

removing 1 item in the box

removing 1 item in the box

adding 1 item in the box

removing 1 item in the box

adding 1 item in the box

0 items still remain in the box

Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles