当前位置 : 主页 > 手机开发 > ROM >

<随便写>同步,异步进程池,线程

来源:互联网 收集:自由互联 发布时间:2021-06-10
from multiprocessing import Poolimport timeimport osdef work(n):print("%s run" % os.getpid())time.sleep(1)return n ** 2if __name__ == ‘__main__‘:p = Pool(5)res_l = []for i in range(10):# res = p.apply(work, args=(i,)) #同步res = p.app
from multiprocessing import Pool
import time
import os


def work(n):
	print("%s run" % os.getpid())
	time.sleep(1)
	return n ** 2


if __name__ == ‘__main__‘:
	p = Pool(5)
	res_l = []
	for i in range(10):
		# res = p.apply(work, args=(i,)) #同步
		res = p.apply_async(work, args=(i,)) #异步
		res_l.append(res)
	p.close()
	p.join()
	for res in res_l:
		print(res.get())

  

 

from threading import Thread
import time
import os


def work(n):
	print("%s run" % os.getpid())
	time.sleep(1)
	return n ** 2


if __name__ == ‘__main__‘:

	res_l = []
	for i in range(10):
		t = Thread(target=work, args=(i,))
		res_l.append(t)
		t.start()
	for res in res_l:
		print(res)
	print("主进程")
网友评论