多线程:#线程的并发是利用cpu上下文的切换(是并发,不是并行)#多线程执行的顺序是无序的#多线程共享全局变量#线程是继承在进程里的,没有进程就没有线程#GIL全局解释器锁#只要在进行耗时的IO操作的时候,能释放GI...

多线程:
#线程的并发是利用cpu上下文的切换(是并发,不是并行)
#多线程执行的顺序是无序的
#多线程共享全局变量
#线程是继承在进程里的,没有进程就没有线程
#GIL全局解释器锁
#只要在进行耗时的IO操作的时候,能释放GIL,所以只要在IO密集型的代码里,用多线程就很合适
#在cpu密集时候不适用多线程
# 线程是操作系统调度的单位
# 线程切换需要的资源一般,效率一般
多进程
#一个程序运行起来之后,代码+用到的资源称之为进程,它是操作系统分配资源的基本单位,不仅可以通过线程完成多任务,进程也是可以的
#进程之间是相互独立的
#cpu密集的时候适合用多进程
# 进程是资源分配的单位
# 进程切换需要的资源最大,效率低
协程
# 协程切换任务资源很小,效率高
# 协程又叫做微线程
# 协程在一个线程中
并发:三个任务1个cpu同时执行
并行:3个任务3个cpu执行
串行:3个任务1个cpu 一个一个执行
线程例:
import time
import threading
def test1():
for i in range(5):
print('test1-%s' % i)
time.sleep(1)
def test2():
for i in range(5)
print('test2-%s' % i)
time.sleep(1)
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=teat2)
t1.start()
t2.start()
进程例:
import multiprocessing import time def test1(n): for i in range(n): time.sleep(1) print('test1-{}'.format(i)) def test2(n): for i in range(n): time.sleep(1) print('test2-{}'.format(i)) if __name__ == '__main__': p1 = multiprocessing.Process(target=test1,args=(5,)) p2 = multiprocessing.Process(target=test2,args=(5,)) p1.start() p2.start()
#进程之间是相互独立的
import time import multiprocessing n = 0 def test1(): global n for i in range(10): n += 1 print('test',n) def test2(): global n for i in range(10): n += 1 print('test2',n) if __name__ == '__main__': p1 = multiprocessing.Process(target=test1) p2 = multiprocessing.Process(target=test2) p1.start() p2.start() print('全局',n)
协程例:
import gevent from gevent import monkey monkey.patch_all() #补丁包 import time def test1(): for i in range(5): time.sleep(1) print('test1',1) def test2(): for i in range(5): time.sleep(2) print('test2',1) g1 = gevent.spawn(test1) g2 = gevent.spawn(test2) g1.join() g2.join()
本文标题为:python中线程 进程 协程


基础教程推荐
- 浅析Python自带性能强悍的标准库itertools 2023-08-04
- python-3.x-使用gunicorn nginx的服务烧瓶应用程序显示404 [ec2] 2023-11-11
- Python实现发送警告通知到企业微信方法详解 2023-08-11
- python数据结构之面向对象 2023-08-09
- selenium鼠标操作实战案例详解 2023-08-04
- python-subprocess.Popen,从子进程中获取变量(子) 2023-11-11
- Python运算符之Inplace运算符的使用教程 2022-10-20
- Python 十大特性 2023-08-11
- python嵌套try...except如何使用详解 2022-08-30
- Python 多线程与多进程 2023-09-04