Sharing State Between Threads
suggest changeAs all threads are running in the same process, all threads have access to the same data.
However, concurrent access to shared data should be protected with a lock to avoid synchronization issues. In the sample, the assignment is inside the lock and the len(obj) prints are not, so those lines can interleave and the counts can skip. The transcript below is one such run. The format string says “values” even when the count is 1.
import threading
obj = {}
obj_lock = threading.Lock()
def objify(key, val):
print("Obj has %d values" % len(obj))
with obj_lock:
obj[key] = val
print("Obj now has %d values" % len(obj))
ts = [threading.Thread(target=objify, args=(str(n), n)) for n in range(4)]
for t in ts:
t.start()
for t in ts:
t.join()
print("Obj final result:")
import pprint; pprint.pprint(obj)
# Out: Obj has 0 values
# Out: Obj has 0 values
# Out: Obj now has 1 values
# Out: Obj now has 2 valuesObj has 2 values
# Out: Obj now has 3 values
# Out:
# Out: Obj has 3 values
# Out: Obj now has 4 values
# Out: Obj final result:
# Out: {'0': 0, '1': 1, '2': 2, '3': 3}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents