我有以下任务,我想通过多线程(python3)更快地完成任务。多线程使进程更慢
import threading, time
q = []
def fill_list():
global q
while True:
q.append(1)
if len(q) >= 1000000000:
return
的第一主不使用多线程:
t1 = time.clock()
fill_list()
tend = time.clock() - t1
print(tend)
,并导致运行时间145秒。
第二调用两个线程:
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)
这需要152秒来完成。
最后,我添加了第三个线程。
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)
而这需要233秒才能完成。
很明显,我添加的线程越多,处理所需的时间越长,但我不知道为什么。这是对多线程的基本误解,还是我的代码中存在一个错误,它只是多次重复执行任务,而不是对同一任务做出贡献?
你已经发现[GIL的(HTTPS://wiki.python .ORG /莫因/ GlobalInterpreterLock)。 – dano