Think about this code:
#!/usr/bin/env python
from threading import Thread
count = 0
def test():
global count
for i in range(10):
count = count + 1
if __name__ == '__main__':
for i in range(1000):
Thread(target = test).start()
print count
I use multiple threads, but the result is always correct. Does that mean I could use python threads without a lock when implementing something like a visitor counter ?
You do need one. Although multithreading works differently in Python, due to the Global Interpreter Lock, operations that are not atomic in Python-bytecode will still need locking.
In you case, you can inspect the bytecode for your function
test(dis.dis(test)):As you can see, the increment is a 2xload, update, store on bytecode-level, so this wont work. The increment is actually 4 separate operations, which you must protect to ensure they are not interrupted.
In your example the problem remains even if you use
count += 1, as the bytecode shows: