import time from gevent import monkey from gevent.pool import Pool monkey.patch_all() import gevent import requests def f(_url: str, _result: list): print('GET: %s' % _url) res = requests.get(_url) time.sleep(10) # 假装网络很慢 10秒才拿到数据 _result.append(res.text) if __name__ == '__main__': start = time.time() p = Pool(2) result = [] apps = [ p.spawn(f, 'https://www.python.org/', result), p.spawn(f, 'https://www.yahoo.com/', result), p.spawn(f, 'https://github.com/', result), ] gevent.joinall(apps) # 等待这些处理结束 end = time.time() cost = end - start print("花费了 %.3f 秒" % cost)
心得: 尽量把耗时的IO操作放到gevent里面,精细化的放进去,不是粗化。
任务函数的返回值参考下面的,我这里直接丢到一个数组里了。
g_list = list() for stock in stocks: dbname = 'daily_data_sz' if stock[0].endswith('.SZ') else 'daily_data_sh' # get_daily_data 是一个函数,后边的都是此函数所需参数 g = gevent.spawn(get_daily_data, pro, stock, end_date, dbname, engine) g_list.append(g) # g是一个Greenlet对象 gevent.joinall(g_list) for i, g in enumerate(g_list): print(i) print(g.value)
https://blog.csdn.net/HYESC/article/details/84866364