Problems understanding how threads work.
I'm learning threading in Python. I decided to calculate the sum of the array using threads, that is, calculate the first half in one thread, and the second in another thread and calculate the time. Here is my code:
import threading
import math
import time
def part_summa0(arr, i, j):
global summ0
for e in range(i, j):
summ0 += arr[e]
def part_summa1(arr, i, j):
global summ1
for e in range(i, j):
summ1 += arr[e]
def threads(arr):
threads = []
threads.append(threading.Thread(target=part_summa0, args=(arr, 0, len(arr)//2)))
threads.append(threading.Thread(target=part_summa1, args=(arr, len(arr)//2, len(arr))))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
l = list(range(1,100000000))
summ0 = 0
summ1 = 0
start = time.time()
part_summa0(l, 0, len(l))
print(summ0)
print(time.time()-start)
summ0 = 0
summ1 = 0
start = time.time()
threads(l)
print(summ0+summ1)
print(time.time()-start)
Here is the output:
4999999950000000
8.55412483215332
4999999950000000
15.346555471420288
Can someone explain to me why threads are slow and how it works?