python多线程获取子任务的返回值
如果多条输入数据,需要预先按需要的线程数拆分数据,单独分别输入到不同的线程中
eg:
import time
import requests
import threading
class MyThread(threading.Thread):
def __init__(self,func,args=()):
super(MyThread,self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result # 如果子线程不使用join方法,此处可能会报没有self.result的错误
except Exception:
return None
#进程函数
def func(districtId,pageIndex,locale):
xxxxx
return list_poiid
def multi_thread_func(districtId,locale,num_thread):
list_poiid_inpage = []
for j in range(0,math.ceil(total_page_target/num_thread)):
st = time.time()
li = []
for i in range(1,num_thread+1 ): # 如果多条输入数据,需要预先按需要的线程数拆分数据,单独分别输入到不同的线程中
if (num_thread*j+i)<= 15:
t = MyThread(func, args=(districtId, 4*j+i, locale))
li.append(t)
t.start()
for t in li:
t.join() # 一定要join,不然主线程比子线程跑的快,会拿不到结果
list_poiid_inpage.append(t.get_result())
et = time.time()
return list_poiid_inpage
参考文献:
python多线程详解
https://www.cnblogs.com/luyuze95/p/11289143.html
获取多线程子任务的返回值
https://blog.csdn.net/u012050154/article/details/80032072
https://www.jianshu.com/p/411bbbc73003
https://www.oudahe.com/p/41926/
线程阻塞
https://blog.csdn.net/sunshine_2211468152/article/details/87299708