python - 为什么这些线程不能并行工作?
问题描述
为什么这段代码不能并行工作?
当奇数线程开始计算它的大数时,其他线程出于某种原因只是等待它完成,尽管它们应该做自己的事情。我错过了什么?
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()
解决方案
Python 线程实际上并没有引入真正的并行性。由于 GIL(全局解释器锁),每个处理器内核只能有一个解释器线程。请参阅GlobalInterpreterLock。
正在发生的事情是工作被分配给你的各个线程,然后他们在 GIL 上一次执行一个。引用 realpython.com 的An Intro to Threading in Python。
线程是一个单独的执行流程。这意味着您的程序将同时发生两件事。但是对于大多数 Python 3 实现来说,不同的线程实际上并不同时执行:它们只是看起来。
对于真正的并行性,您必须使用该multiprocessing
库,它将:
通过使用子进程而不是线程来有效地避开全局解释器锁。因此,多处理模块允许程序员充分利用给定机器上的多个处理器。
推荐阅读
- kentico - 如何避免外部用户链接到 /cmspages/logon.aspx
- java - Spring Boot + JAX-WS 没有额外的 servlet?
- java - 如何使用弹簧反应通量阅读器运行弹簧批处理?
- python-3.x - Python 没有保存 csv 文件,如何解决这个问题?
- bitbucket - 使用 sourcetree 和 gitflow 进行发布
- python - 如何在google平台-ai平台-笔记本实例中安装库
- python - 获取一定范围内非零二进制掩码的坐标
- c# - 如何为 Kestrel 主机添加 NTLM 支持?
- php - php/MySQL count() 进行排名
- python - 如何修复'str'对象在pytorch中没有属性'seek'错误?