我有以下任務,我想通過多線程(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