首页 > 解决方案 > 为什么这些线程不能并行工作?

问题描述

为什么这段代码不能并行工作?

当奇数线程开始计算它的大数时,其他线程出于某种原因只是等待它完成,尽管它们应该做自己的事情。我错过了什么?

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()

标签: pythonmultithreadingpython-multithreading

解决方案


Python 线程实际上并没有引入真正的并行性。由于 GIL(全局解释器锁),每个处理器内核只能有一个解释器线程。请参阅GlobalInterpreterLock

正在发生的事情是工作被分配给你的各个线程,然后他们在 GIL 上一次执行一个。引用 realpython.com 的An Intro to Threading in Python

线程是一个单独的执行流程。这意味着您的程序将同时发生两件事。但是对于大多数 Python 3 实现来说,不同的线程实际上并不同时执行:它们只是看起来。

对于真正的并行性,您必须使用该multiprocessing 库,它将:

通过使用子进程而不是线程来有效地避开全局解释器锁。因此,多处理模块允许程序员充分利用给定机器上的多个处理器。


推荐阅读