为什么这些线程无法并行工作?
Why do these threads fail to work in parallel?
为什么这段代码不能并行工作?
当奇数线程开始计算它的大数时,其他线程出于某种原因只是等待它完成,尽管它们应该做自己的事情。我错过了什么?
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.
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
库,它将:
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.
此行为与 cPyhton 的特定实现细节有关(使用其他答案中解释的全局解释器锁)
但是,当 运行 使用 jython(Java 实现 Python)这个脚本时,您会得到预期的结果。
$ jython main.py
(0, 'started')
(2, 'started')
(3, 'started')
(1, 'started')
(4, 'started')
(0, 'finished')
(2, 'finished')
(4, 'finished')
...
为什么这段代码不能并行工作?
当奇数线程开始计算它的大数时,其他线程出于某种原因只是等待它完成,尽管它们应该做自己的事情。我错过了什么?
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.
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
库,它将:
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.
此行为与 cPyhton 的特定实现细节有关(使用其他答案中解释的全局解释器锁)
但是,当 运行 使用 jython(Java 实现 Python)这个脚本时,您会得到预期的结果。
$ jython main.py
(0, 'started')
(2, 'started')
(3, 'started')
(1, 'started')
(4, 'started')
(0, 'finished')
(2, 'finished')
(4, 'finished')
...