import threading
# Shared variable
shared_variable = 0
NUM_THREADS = 999
NUM_INCREMENT = 1_000_000
# Function to increment the shared variable
def increment():
global shared_variable
for _ in range(NUM_INCREMENT):
shared_variable += 1
# Creating multiple threads to increment the shared variable concurrently
threads = []
for _ in range(NUM_THREADS):
thread = threading.Thread(target=increment)
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
# Display the value of the shared variable after concurrent increments
print(
f"The value of the shared variable is: {shared_variable}, expected : {NUM_THREADS * NUM_INCREMENT}"
)
当我加入线程时,此代码总是打印预期的数字。但如果我评论这段代码,那么一些增量就会失败(这是我实际期望的结果!)。
# for thread in threads:
# thread.join()
为什么当我添加 join 时这段代码会以线程安全的方式运行?
thread.join()
等待thread
完成其工作。如果你要求某人做某事,你会“立即”抱怨他们没有正确完成工作吗?或者你会等他们完成工作后再做出判断吗?
如果您的程序在打印 thread.join()
的值之前在每个线程上调用
shared_variable
,那么这将为线程提供时间来完成其工作。如果它没有加入线程,并且您在启动线程后立即打印
shared_variable
,那么...您将得到您所得到的一切。