gpt4 book ai didi

python - Python线程可以在同一个进程上工作吗?

转载 作者:行者123 更新时间:2023-12-03 13:09:21 24 4
gpt4 key购买 nike

我试图想出一种方法让线程在不干扰的情况下工作在同一个目标上。在这种情况下,我使用 4 个线程将 0 到 90,000 之间的每个数字相加。这段代码运行但它几乎立即结束(运行时间:0.00399994850159 秒)并且只输出 0。最初我想用一个全局变量来做,但我担心线程相互干扰(即两个线程加倍的可能性很小由于读/写的奇怪时间而计数或跳过一个数字)。因此,我事先分配了工作量。如果有更好的方法来做到这一点,请分享。这是我尝试在多线程中获得一些经验的简单方法。谢谢

import threading
import time

start_time = time.time()

tot1 = 0
tot2 = 0
tot3 = 0
tot4 = 0

def Func(x,y,tot):
tot = 0
i = y-x
while z in range(0,i):
tot = tot + i + z

# class Tester(threading.Thread):
# def run(self):
# print(n)

w = threading.Thread(target=Func, args=(0,22499,tot1))
x = threading.Thread(target=Func, args=(22500,44999,tot2))
y = threading.Thread(target=Func, args=(45000,67499,tot3))
z = threading.Thread(target=Func, args=(67500,89999,tot4))

w.start()
x.start()
y.start()
z.start()

w.join()
x.join()
y.join()
z.join()

# while (w.isAlive() == False | x.isAlive() == False | y.isAlive() == False | z.isAlive() == False): {}

total = tot1 + tot2 + tot3 + tot4

print total

print("--- %s seconds ---" % (time.time() - start_time))

最佳答案

您有一个错误,使该程序几乎立即结束。看while z in range(0,i):Func . z没有在函数中定义,它只是靠运气(真的很倒霉)你碰巧有一个全局变量 z = threading.Thread(target=Func, args=(67500,89999,tot4))这掩盖了问题。您正在测试线程对象是否在整数列表中......而不是!

下一个问题是全局变量。首先,您绝对正确,使用单个全局变量不是线程安全的。线程会混淆彼此的计算。但是您误解了全局变量的工作原理。当你这样做 threading.Thread(target=Func, args=(67500,89999,tot4)) ,python传递tot4当前引用的对象到函数,但函数不知道它来自哪个全局。您只更新局部变量 tot并在函数完成时丢弃它。

一种解决方案是使用全局容器来保存计算,如下例所示。不幸的是,这实际上比在一个线程中完成所有工作要慢。 python 全局解释器锁 (GIL) 一次只允许 1 个线程运行,并且只会减慢在纯 python 中实现的 CPU 密集型任务。

你可以看看multiprocessing模块将其拆分为多个进程。如果运行计算的成本与启动流程和传递数据的成本相比很大,那么这种方法效果很好。

这是您的示例的工作副本:

import threading
import time

start_time = time.time()

tot = [0] * 4

def Func(x,y,tot_index):
my_total = 0
i = y-x
for z in range(0,i):
my_total = my_total + i + z
tot[tot_index] = my_total

# class Tester(threading.Thread):
# def run(self):
# print(n)

w = threading.Thread(target=Func, args=(0,22499,0))
x = threading.Thread(target=Func, args=(22500,44999,1))
y = threading.Thread(target=Func, args=(45000,67499,2))
z = threading.Thread(target=Func, args=(67500,89999,3))

w.start()
x.start()
y.start()
z.start()

w.join()
x.join()
y.join()
z.join()

# while (w.isAlive() == False | x.isAlive() == False | y.isAlive() == False | z.isAlive() == False): {}

total = sum(tot)


print total

print("--- %s seconds ---" % (time.time() - start_time))

关于python - Python线程可以在同一个进程上工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41094292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com