1

I am learning how to test threads in Python as I have never done it before. I have put a lock in but it says that I have an assertion error which is fine. I am wondering if the following code is correct

import threading

i = 0

def test():
    global i
    for _ in range(100000):
        with threading.Lock():
            i += 1

threads = [threading.Thread(target=test) for t in range(10)]
for t in threads:
    t.start()

for t in threads:
    t.join()

assert i == 1000000, i
2
  • I think you misunderstand what Lock does. It doesn't lock access to i, it just locks access to the lock itself, until it's released. So the 1,000,000 locks your code creates don't do anything useful, they just waste time. Commented Jun 19, 2018 at 7:57
  • 1
    Could you roll back your question, since this way this question won't be helpful to anyone with a similar problem. Commented Jun 19, 2018 at 8:11

1 Answer 1

1

Your problem is that you create a new Lock on every iteration, which is always unlocked.

This way it'll work, because your Threads will try to aquire the same lock.

import threading

i = 0

lock = threading.Lock()

def test():
    global i
    for _ in range(100000):
        with lock:
            i += 1

threads = [threading.Thread(target=test) for t in range(10)]
for t in threads:
    t.start()

for t in threads:
    t.join()

print(i)
Sign up to request clarification or add additional context in comments.

5 Comments

Where should I print to test it out? @pask
After joining the threads. I added a print statement in the answer.
@user9590653 Or just put your assert at the end of the code.
what about the assert? thats part of my testing
You can also put your assert back in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.