1 import random 2 import threading 3 4 results = [] 5 6 def compute(): 7 #random.randint(1,100) 返回一个随机值 8 results.append(sum([random.randint(1,100) for i in range(1000000)])) 9 #开启八个线程 10 workers = [threading.Thread(target=compute) for i in range(8)] 11 12 for worker in workers: 13 worker.start() 14 15 for worker in workers: 16 worker.join() 17 18 print results 19 20 21 >>> 22 [50525916, 50480384, 50472573, 50504944, 50472008, 50478334, 50525776, 50519455] 23 >>> sum([50525916, 50480384, 50472573, 50504944, 50472008, 50478334, 50525776, 50519455]) 24 403979390 25 >>>
1 import multiprocessing 2 import random 3 4 def compute(): 5 return sum( 6 [random.randint(1,100) for i in range(1000000)]) 7 8 #创建8个进程pool池 9 pool = multiprocessing.Pool(8) 10 11 #开始八个进程 12 print pool.map(compute,range(8))
时间: 2024-10-10 16:30:38