为什么这些线程无法并行工作? [英] Why do these threads fail to work in parallel?

查看:97
本文介绍了为什么这些线程无法并行工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why this code doesn't work in parallel?

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

When the thread with odd number starts calculating its big number, other threads for some reason just wait for it to finish although they are supposed to do their own stuff. What am I missing?

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.

Python threads don't actually introduce true parallelism. Owing to the GIL (global interpreter lock) there can only be one interpreter thread per processor core. See GlobalInterpreterLock.

正在发生的事情是工作被分配到您的各个线程之间,然后这些线程在 GIL 上一次执行一个.引用 realpython.com 的 Python 线程简介.

What's happening is the work is being divided up among your various threads, who then execute one at a time on the GIL. To quote realpython.com's An Intro to Threading in Python.

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

A thread is a separate flow of execution. This means that your program will have two things happening at once. But for most Python 3 implementations the different threads do not actually execute at the same time: they merely appear to.

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

For true parallelism, you'd have to use the multiprocessing library, which will:

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

effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine.

这篇关于为什么这些线程无法并行工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆