# This is not at all my actual code, but the structure is the same import threading def main(): lock = threading.Lock() threads_ran = 0 def thread_fn(): nonlocal threads_ran with lock: print("threads_ran is {} on entry".format(threads_ran)) thread_ran += 1 print("threads_ran is {} on exit".format(threads_ran)) threads = [] for _ in range(10): threads.append(threading.Thread(target=thread_fn)) for t in threads: t.start() for t in threads: t.join() main()