
生成器可以实现代码协成运行
占用资源和时长从大到小:
进程 > 线程 > 协成
两个函数启动时间不同,用 线程和进程没有区别,用协成会等待时间长的运行后在重复,必须遵守一个一个运行。
import time
import threading
import multiprocessing
'''
def task_1():
while True:
print("--1--")
time.sleep(0.1)
yield # 可以不用传任何参数
def task_2():
while True:
print("--2--")
time.sleep(1)
yield # return无法做到
def main():
t1 = task_1()
t2 = task_2()
while True:
next(t1)
next(t2)
'''
'''
多线程启动方法:
def task_1():
while True:
print("--1--")
time.sleep(0.1)
def task_2():
while True:
print("--2--")
time.sleep(0.5)
def main():
t1 = threading.Thread(target=task_1)
t2 = threading.Thread(target=task_2)
t1.start()
t2.start()
'''
'''
多进程运行
def task_1():
while True:
print("--1--")
time.sleep(0.1)
def task_2():
while True:
print("--2--")
time.sleep(0.5)
def main():
t1 = multiprocessing.Process(target=task_1)
t2 = multiprocessing.Process(target=task_2)
t1.start()
t2.start()
'''
if __name__ == '__main__':
main()
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)