进程、线程、协程代码
多进程代码
import multiprocessing
import time
import os
def run():
for i in range(5):
print("当前进程:{}".format(os.getpid()), end='---')
print('跑步')
time.sleep(1)
def swim():
for i in range(5):
print("当前进程:{}".format(os.getpid()), end='---')
print('游泳')
time.sleep(1)
if __name__ == '__main__':
data_1 = multiprocessing.Process(target=run)
data_2 = multiprocessing.Process(target=swim)
data_1.start()
data_2.start()
多线程代码
import threading
import time
import os
def run():
for i in range(5):
print("当前进程:{}".format(os.getpid()), end='---')
print('跑步')
time.sleep(1)
def swim():
for i in range(5):
print("当前进程:{}".format(os.getpid()), end='---')
print('游泳')
time.sleep(1)
if __name__ == '__main__':
thread_1 = threading.Thread(target=run)
thread_2 = threading.Thread(target=swim)
thread_1.start()
thread_2.start()
协程代码
from gevent import monkey
# 猴子补丁
monkey.patch_all()
import time
import gevent
import os
def run():
for i in range(5):
print("当前进程:{}".format(os.getpid()), end='---')
print('跑步')
gevent.sleep(1)
def swim():
for i in range(5):
print("当前进程:{}".format(os.getpid()), end='---')
print('游泳')
gevent.sleep(1)
# 创建携程并指派任务
sp1 = gevent.spawn(run)
sp2 = gevent.spawn(swim)
# 等待协程执行完成再关闭主线程
sp1.join()
sp2.join()
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。
文章标题:进程、线程、协程代码
本文作者:伟生
发布时间:2019-10-31, 20:12:35
最后更新:2019-10-31, 20:43:56
原始链接:http://yoursite.com/2019/10/31/basic_02_relation/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。