Python 多线程处理具有相似代码的不同输出
原来的代码是Python 多线程处理具有相似代码的不同输出,python,multithreading,Python,Multithreading,原来的代码是 import time, threading balance = 0 def change_it(n): global balance balance = balance + n balance = balance - n def run_thread(n): for i in range(2000000): change_it(n) t1 = threading.Thread(target=run_thread, args=
import time, threading
balance = 0
def change_it(n):
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(2000000):
change_it(n)
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)
这会产生随机结果,因为线程相互影响
但是当我试着
t1 = threading.Thread(target=run_thread(5))
t2 = threading.Thread(target=run_thread(8))
每次都能正常工作。为什么它们不同?您的第二次尝试实际上没有执行任何线程。您的命令不是启动线程,而是当场执行
run\u-thread
函数。这就是为什么必须使用args元组将参数传递给线程函数,使其正常工作。如果你说
target=run_thread(5)
target获取执行run\u thread(5)
的返回值,在本例中为None,因为您的函数不返回任何内容-但它当然会在执行函数时在函数内进行计算以获取返回值
这也意味着您的第二次尝试不会并行运行任务。它们一个接一个地按顺序运行。哦,我明白了。我认为threading.Thread(Target=something())也可以定义线程。谢谢你的回答。您可以使用该构造,但是您的something()必须返回要调用的函数。这在某些情况下可能有用,但与您的问题无关。在本例中,如果线程中执行的是
某个东西,则必须使用args结构来传递参数。