python中线程 进程 协程

多线程:
#线程的并发是利用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()
原文地址:https://www.cnblogs.com/t-ym/p/11825776.html