【发布时间】:2020-11-17 21:58:54
【问题描述】:
为什么这段代码不能并行工作?
当奇数线程开始计算它的大数时,其他线程出于某种原因只是等待它完成,尽管它们应该做自己的事情。我错过了什么?
import threading, math, time
class MyThread(threading.Thread):
def __init__(self, num):
super(MyThread, self).__init__()
self.num = num
def run(self):
while True:
with mutex:
print(self.num, 'started')
math.factorial(self.num % 2 * 100000000)
with mutex:
print(self.num, 'finished')
time.sleep(2)
mutex = threading.Lock()
threads = [MyThread(i) for i in range(5)]
for th in threads:
th.start()
【问题讨论】:
-
你知道GlobalInterpreterLock吗?可能是您需要使用多处理而不是线程,这可以真正并行执行。
-
不幸的是,我只能使用多线程
-
那是关键信息,你为什么没有在你的帖子中提到它?你肯定需要包括这个(以及任何理由),因为你会浪费每个人的时间,他们会尝试建议多处理。
标签: python multithreading python-multithreading