我想要使用線程在python中獲得更好的性能。Python中的線程-
我的程序需要返回線程執行的每個函數的值。
而且我需要知道線程何時完成。
有3種方法我試圖執行這個小程序。
import thread
import datetime
from threading import Thread
import threading
from multiprocessing.pool import ThreadPool
def func1(word):
i=0
while i<100000:
if 1<2:
i=i+1
return "func1"
def func2():
i=0
while i<100000:
if 1<2:
i=i+1
return "func2"
word="hiiii"
"""
#--------------------------------example1--------------------------------
pool = ThreadPool(processes=2)
print str(datetime.datetime.now().time())
async_result1 = pool.apply_async(func1, (word,))
async_result2 = pool.apply_async(func2)
print async_result1.get()
print async_result2.get()
print str(datetime.datetime.now().time())
print func1(word)
print func2()
print str(datetime.datetime.now().time())
#with threads-71000
#without threads- 40000
#--------------------------------example1--------------------------------
"""
"""
#--------------------------------example2--------------------------------
t1 = Thread(target=func1, args=(word,))
t2 = Thread(target=func2, args=())
print str(datetime.datetime.now().time())
t1.start()
t2.start()
t1.join()
t2.join()
print str(datetime.datetime.now().time())
func1(word)
func2()
print str(datetime.datetime.now().time())
#with threads-75000
#without threads-42000
#--------------------------------example2--------------------------------
"""
"""
#--------------------------------example3 without sending value--------------------------------
print str(datetime.datetime.now().time())
t1 = threading.Thread(name=func1,target=func1)
t2= threading.Thread(name=func2,target=func2)
t1.start()
t2.start()
t1.join()
t2.join()
print str(datetime.datetime.now().time())
func1()
func2()
print str(datetime.datetime.now().time())
#with threads- 73000
#without threads- 42000
#--------------------------------example3 without sending value------------- -------------------
"""
但是,你可以看到更好的運行方式是沒有線程的! 爲什麼?我做錯了什麼?如何使用線程?
線程通常只在任務是IO綁定時纔有用;這段代碼顯然是CPU綁定的。 –
GIL(全局解釋器鎖),python線程不是本地線程 –