I have the following task that I would like to make faster via multi threading (python3).
import threading, time
q = []
def fill_list():
global q
while True:
q.append(1)
if len(q) >= 1000000000:
return
The first main does not utilize multithreading:
t1 = time.clock()
fill_list()
tend = time.clock() - t1
print(tend)
And results in 145 seconds of run time.
The second invokes two threads:
t1 = time.clock()
thread1 = threading.Thread(target=fill_list, args=())
thread2 = threading.Thread(target=fill_list, args=())
thread1.start()
thread2.start()
thread1.join()
thread2.join()
tend = time.clock() - t1
print(tend)
This takes 152 seconds to complete.
Finally, I added a third thread.
t1 = time.clock()
thread1 = threading.Thread(target=fill_list, args=())
thread2 = threading.Thread(target=fill_list, args=())
thread3 = threading.Thread(target=fill_list, args=())
thread1.start()
thread2.start()
thread3.start()
thread1.join()
thread2.join()
thread3.join()
tend = time.clock() - t1
print(tend)
And this took 233 seconds to complete.
Obviously the more threads I add, the longer the process takes, though I am not sure why. Is this a fundamental misunderstanding of multithreading, or is there a bug in my code that is simply repeating the task multiple times instead of contributing to the same task?