How to achieve true parallelism using thread in Python?

I am learning a thread library in Python. I don’t understand how to start two threads in parallel?

Here are my python programs:

Program without streaming ( fibsimple.py )

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

fib(35)
fib(35)

print "Done"

Duration:

$ time python fibsimple.py 
Done

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

The same program with streaming processing ( 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"

Duration:

$ time python fibthread.py 
Done

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

I don’t understand why the thread program takes longer? It should be almost half if the threads are running in parallel.

But if I implement the same program with a multiprocessor library, the time will be half.

with multiprocess ( 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"

Working hours

 $ time python fibmultiporcess.py 
 Done

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

Can someone explain how to execute threads in parallel? How are multiprocessor and thread-parallelism different? Any help would be appreciated.

+4
1

, GIL.

GIL Global Interpreter Lock, . , ONE . , .

, ?

, .

, , , GIL. , .

python

GIL , Python GIL - David Beazley. , .

+2

Source: https://habr.com/ru/post/1681004/


All Articles