我想在 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------------- -------------------
"""
但是,您可以看到更好的运行方式是没有线程! 为什么??我做错了什么?如何使用线程?
最佳答案
当您有多个任务争夺 CPU 但大部分时间都在等待某些外部事件(例如网络读取或数据库写入)时,线程主要有用。
当多个线程处于事件状态时,每个(一定数量)的操作码都会花费时间来决定切换到另一个线程(假设还有其他可运行的线程)。如果您的两个线程除了计算之外都不执行任何操作,那么实际上就无法通过在线程之间切换来节省时间。因为所有线程都在同一个进程中运行,并且 Python 进程(通常)无法利用多个 CPU,所以您不会看到任何加速(实际上,可能会由于线程切换事件而观察到速度减慢)。
tl;dr:CPU 密集型任务无法通过多线程加速。
关于python - python 中的线程-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39572769/