同步异步

import time

def func():
	time.sleep(3)
	print(‘hello world‘)


if __name__ == ‘__main__‘:
	res = func()  # 同步调用
	print(‘hahaha‘)
# 第一种
from multiprocessing import Process
import time


def task(name):
	print(‘%s is running‘%name)
	time.sleep(3)
	print(‘%s is over‘%name)


if __name__ == ‘__main__‘:
	# 1 创建一个对象
	p = Process(target=task, args=(‘jason‘,))
	# 容器类型哪怕里面只有1个元素 建议要用逗号隔开
	# 2 开启进程
	p.start()  # 告诉操作系统帮你创建一个进程  异步
	print(‘主‘)
"""
windows操作系统下 创建进程一定要在main内创建
因为windows下创建进程类似于模块导入的方式
会从上往下依次执行代码
linux中则是直接将代码完整的拷贝一份
"""
# 第二种方式 类的继承
   from multiprocessing import Process
   import time
  
  
 class MyProcess(Process):
     def run(self):
         print(‘hello bf girl‘)
         time.sleep(1)
         print(‘get out!‘)


 if __name__ == ‘__main__‘:
     p = MyProcess()
     p.start()
     print(‘主‘)


from multiprocessing import Process
import time


def task(name, n):
	print(‘%s is running‘%name)
	time.sleep(n)
	print(‘%s is over‘%name)


if __name__ == ‘__main__‘:
	# p1 = Process(target=task, args=(‘jason‘, 1))
	# p2 = Process(target=task, args=(‘egon‘, 2))
	# p3 = Process(target=task, args=(‘tank‘, 3))
	# start_time = time.time()
	# p1.start()
	# p2.start()
	# p3.start()  # 仅仅是告诉操作系统要创建进程
	# # time.sleep(50000000000000000000)
	# # p.join()  # 主进程等待子进程p运行结束之后再继续往后执行
	# p1.join()
	# p2.join()
	# p3.join()
	start_time = time.time()
	p_list = []
	for i in range(1, 4):
		p = Process(target=task, args=(‘子进程%s‘%i, i))
		p.start()
		p_list.append(p)
	for p in p_list:
		p.join()
	print(‘主‘, time.time() - start_time)

from multiprocessing import Process


money = 100


def task():
	global money  # 局部修改全局
	money = 666
	print(‘子‘,money)


if __name__ == ‘__main__‘:
	p = Process(target=task)
	p.start()
	p.join()
	print(money)

同步异步

上一篇:第二周


下一篇:182. 跟着三叶学最短路径问题(存图方式)