Mariska
Mariska

Reputation: 1949

Python threading: a thread increments the count and the other decrements

I have a supposedly simple threading example in python, where a thread increments the count every second and the other decrements every 5 seconds. Here is the code

# threading example
import threading
import time

lock = threading.Lock()
count = 0

def a():
  global count
  while(1):
    lock.acquire()
    try:
      count += 1
      print('a: ', count )
    finally:
      time.sleep(1)
      lock.release()


def b():
  global count
  while(1):
    lock.acquire()
    try:
      count -= 1
      print('b: ', count )
    finally:
      time.sleep(5)
      lock.release()

t = threading.Thread(name='a', target=a)
w = threading.Thread(name='b', target=b)

t.start()
w.start()

However, it seems like only thread t prints out stuff, while thread w does not. Here is the output:

a:  1
a:  2
a:  3
a:  4
a:  5
a:  6
a:  7
a:  8
a:  9

What went wrong?

Upvotes: 1

Views: 1104

Answers (1)

T McKeown
T McKeown

Reputation: 12857

You need to release the lock before sleeping otherwise you never really are releasing the lock.

Change:

finally:
  time.sleep(1)
  lock.release()

To:

finally:
  lock.release()
  time.sleep(1)

And do the same for the other thread. You only need to lock during the increment/decrement, it's the only operation that has thread safety concerns.

Upvotes: 4

Related Questions