【问题标题】:How to achive true parallelism with thread in Python?如何在 Python 中使用线程实现真正的并行性?
【发布时间】:2017-12-12 11:47:38
【问题描述】:

我正在学习 Python 中的线程库。我不明白,如何并行运行两个线程?

这是我的 python 程序:

没有线程的程序 (fibsimple.py)

def fib(n):
    if n < 2:
        return n
    else: 
        return fib(n-1) + fib(n-2)

fib(35)
fib(35)

print "Done"

运行时间:

$ time python fibsimple.py 
Done

real    0m7.935s
user    0m7.922s
sys 0m0.008s

与线程相同的程序(fibthread.py

from threading import Thread
def fib(n):
    if n < 2:
        return n
    else: 
        return fib(n-1) + fib(n-2)

t1 = Thread(target = fib, args = (35, ))
t1.start()

t2 = Thread(target = fib, args = (35, ))
t2.start()

t1.join()
t2.join()

print "Done"

运行时间:

$ time python fibthread.py 
Done

real    0m12.313s
user    0m10.894s
sys 0m5.043s

我不明白为什么线程程序需要更多时间?如果线程并行运行,它应该几乎是一半。

但是如果我用多处理库实现相同的程序,时间就会减半。

多进程程序(fibmultiprocess.py)

from multiprocessing import Process

def fib(n):
    if n < 2:
        return n
    else: 
        return fib(n-1) + fib(n-2)

p1 = Process(target = fib, args = (35, ))
p1.start()

p2 = Process(target = fib, args = (35, ))
p2.start()

p1.join()
p2.join()

print "Done"

运行时间

 $ time python fibmultiporcess.py 
 Done

 real   0m4.303s
 user   0m8.065s
 sys    0m0.007s

谁能解释一下,如何并行运行线程?多处理和线程并行有什么不同?任何帮助将不胜感激。

【问题讨论】:

标签: python parallel-processing python-multiprocessing python-multithreading


【解决方案1】:

要解释多线程的怪异运行时间,你必须知道GIL

GIL 代表 Global Interpreter Lock,它旨在序列化从不同线程对解释器内部的访问。也就是说,解释器一次只运行 ONE 线程。在多核系统上,这意味着多线程不能有效地利用多核。

但是为什么运行时间比没有多线程的要长呢?

这是因为在线程之间切换时会消耗额外的时间。

当然,由于使用多处理创建多个解释器,它不受 GIL 的影响。这就是为什么速度可以像预期的那样翻倍。

参考

python中多线程和多进程的好比较link

要了解有关 GIL 和其他一些实验的更多信息,请查看 Understanding the Python GIL - David Beazley。这是最好的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    • 2013-01-23
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多