为什么当我添加 thread.join() 时,这个多线程代码会表现得更安全?

问题描述 投票:0回答:1
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 时这段代码会以线程安全的方式运行?

python thread-safety
1个回答
0
投票

thread.join()
等待
thread
完成其工作。如果你要求某人做某事,你会“立即”抱怨他们没有正确完成工作吗?或者你会等他们完成工作后再做出判断吗? 如果您的程序在打印

thread.join()

的值之前在每个线程上调用

shared_variable
,那么这将为线程提供时间来完成其工作。如果它没有加入线程,并且您在启动线程后
立即
打印shared_variable,那么...您将得到您所得到的一切。
    

© www.soinside.com 2019 - 2024. All rights reserved.