开启8个线程,每个线程开启8个协程
计算数的平方
代码:
import gevent.pool import gevent.monkey gevent.monkey.patch_all() import concurrent.futures def go(n): return n*n def geventgo(list): mypool = gevent.pool.Pool(8) #协程池,开启8个协程 results = mypool.map(go,list) return results if __name__ == "__main__": datalist = [] for i in range(10): mylist = [x for x in range(10 * i, 10 * (i + 1))] datalist.append(mylist) #datalist = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74, 75, 76, 77, 78, 79], [80, 81, 82, 83, 84, 85, 86, 87, 88, 89], [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]] with concurrent.futures.ThreadPoolExecutor(8) as pool: # 开启8个线程 results = pool.map(geventgo,datalist) for result in results: print(result)
结果: