进程状态图
同步和异步
描述的是任务的提交方式
-
同步: 任务提交之后,原地等待任务的返回结果,等待的过程中不做任何事情
-
异步: 任务提交之后,不原地等待任务的返回结果,直接去做其它事情
- 任务的返回结果会有一个异步回调机制自动处理
阻塞和非阻塞
描述的是程序的运行状态
- 阻塞: 阻塞态
- 非阻塞: 就绪态、运行态
开启进程的两种方式
- windows系统下,创建进程一定要在main创建,因为windows下创建进程类似于模块导入的方式,会从上往下依次执行代码
- Linux中则是直接将代码完整的拷贝一份
方式1:
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__':
# 创建一个对象
p = Process(target=task, args=('wuxing',))
# 开启进程
p.start() # 告诉操作系统帮你创建一个进程
print('主')
方式2:
from multiprocessing import Process
import time
class MyProcess(Process):
def run(self):
print('hello world')
time.sleep(1)
print('get out!')
if __name__ == '__main__':
p = MyProcess()
p.start()
print('主')
- 创建进程就是在内存中申请一块内存空间将需要运行的代码放进去
- 一个进程对应在内存中就是一块独立的内存空间
- 进程与进程之间数据默认情况下无法直接交互,如果想交互可以借助第三方工具、模块
join方法
join是让主进程等待子进程代码运行结束之后,再继续运行,不影响其它子进程的执行
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=('xia', 1))
# p2 = Process(target=task, args=('dong', 2))
# p3 = Process(target=task, args=('zhi', 3))
# start_time = time.time()
# p1.start()
# p2.start()
# p3.start()
# # 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)
进程对象及其它方法
from multiprocessing import Process, current_process
import time
import os
def task():
# print('%s is running' %current_process().pid) #查看当前进程的进程号
print('%s is running' %os.getpid()) #查看当前进程的进程号
#print('子进程的父进程号 %s' %os.getppid()) #查看当前进程的父进程号
time.sleep(30)
if __name__ == '__main__':
p = Process(target=task)
p.start()
p.terminate() # 杀死当前进程
time.sleep(0.1)
print(p.is_alive()) #判断当前进程是否存活
# print('主', current_process().pid)
# print('主', os.getpid())
# print('主主', os.getppid())
僵尸进程与孤儿进程
-
僵尸进程
- 当开设了子进程后,该进程死后不会立刻释放占用的进程号,因为要让父进程能够查看到它开设的子进程的一些基本信息(占用的pid号 运行时间等)
- 所有的进程都会进入僵尸进程阶段
-
孤儿进程
- 子进程存活,父进程意外死亡
- 操作系统会管理孤儿进程回收相关资源
from multiprocessing import Process
import time
def run():
print('hello world')
time.sleep(3)
print('get out')
if __name__ == '__main__':
p = Process(target=run)
p.start()
print('主')
守护进程
随着操作系统的启动而启动,随着操作系统的停止而停止
from multiprocessing import Process
import time
def task(name='egon'):
print('%s总管正在活着' %name)
time.sleep(3)
print('%s总管正在死亡' %name)
if __name__ == '__main__':
# p = Process(target=task, args=('egon',))
p = Process(target=task, kwargs={'name': 'egon'})
p.daemon = True # 将进程p设置为守护进程,必须放在start之前,否则报错
p.start()
print('皇帝jason寿终正寝')
互斥锁
多个进程操作同一份数据时,会出现数据错乱的问题
解决方式就是加锁处理: 将并发变成串行,牺牲效率但是保证数据安全
from multiprocessing import Process, Lock
import json
import time
import random
#查票
def search(i):
# 文件操作读取票数
with open('data', 'r', encoding='utf8') as f:
dic = json.load(f)
print('用户%s查询余票: %s' %(i, dic.get('ticket_num')))
# 买票 1.先查 2.再买
def buy(i):
# 查票
with open('data', 'r', encoding='utf8') as f:
dic = json.load(f)
# 模拟网络延迟
time.sleep(random.randint(1,3))
# 判断当前是否有票
if dic.get('ticket_num') > 0:
#修改数据库买票
dic['ticket_num'] -= 1
# 写入数据库
with open('data', 'w', encoding='utf8') as f:
json.dump(dic, f)
print('用户%s买票成功' %i)
else:
print('用户%s买票失败' %i)
def run(i, mutex):
search(i)
# 给买票环节加锁处理
# 抢锁
mutex.acquire()
buy(i)
# 释放锁
mutex.release()
if __name__ == '__main__':
# 在主进程中生成一把锁,让所有的子进程抢,谁先抢到谁先买票
mutex = Lock()
for i in range(1, 10):
p = Process(target=run, args=(i, mutex))
p.start()
进程间通信
- 队列Queue模块
队列:先进先出
堆栈:先进后出
from multiprocessing import Queue
# 创建一个队列
q = Queue(5) # 括号内可以传数字,表示生成的队列最大可以同时存放的数据量
# 往队列中存数据
q.put(111)
q.put(222)
q.put(333)
# print(q.full()) # 判断当前队列是否满了
# print(q.empty()) # 判断当前队列是否空
q.put(444)
q.put(555)
# print(q.full()) # 判断当前队列是否满了
# q.put(666) # 当队列放满了之后,如果还有数据要放,程序会阻塞,直到有位置让出来,不会报错
# 去队列中取数据
v1 = q.get()
v2 = q.get()
v3 = q.get()
v4 = q.get()
v5 = q.get()
# print(q.empty()) # 判断当前队列是否空
# v6 = q.get_nowait() # 没有数据直接报错 queue.Empty
# v6 = q.get(timeout=3) # 没有数据之后,等待三秒之后报错
# v6 = q.get() # 队列中没有数据时,get方法会阻塞
try:
v6 = q.get(timeout=3)
print(v6)
except Exception as e:
print('没有了')
# print(v1, v2, v3, v4, v5, v6)
IPC机制
from multiprocessing import Process
from multiprocessing import Queue
'''
1.主进程跟子进程借助队列通信
2.子进程跟子进程借助队列通信
'''
def producer(q):
q.put('我是23号技师,很高兴为您服务')
# print('hello big baby~')
def consumer(q):
print(q.get())
if __name__ == '__main__':
q = Queue()
p = Process(target=producer, args=(q,))
p1 = Process(target=consumer, args=(q,))
p.start()
p1.start()
# print(q.get())
生产者消费者模型
- 生产者: 生产/制造数据
- 消费者: 消费/处理数据
- 消息队列:暂存数据
from multiprocessing import Process, Queue, JoinableQueue
import time
import random
def producer(name, food, q):
for i in range(5):
data = '%s生产了%s%s'%(name, food, i)
time.sleep(random.randint(1,3))
print(data)
q.put(data)
def consumer(name, q):
while True:
food = q.get() # 没有数据就会卡主
# if food is None:
# break
time.sleep(random.randint(1,3))
print('%s吃了%s'%(name, food))
q.task_done() # 告诉队列已经从里面取出一个数据并且处理完毕了
if __name__ == '__main__':
q = JoinableQueue()
p1 = Process(target=producer, args=('大厨egon', '包子', q))
p2 = Process(target=producer, args=('马叉虫tank', '泔水', q))
c1 = Process(target=consumer, args=('春哥', q))
c2 = Process(target=consumer, args=('新哥', q))
p1.start()
p2.start()
c1.daemon = True
c2.daemon = True
c1.start()
c2.start()
p1.join()
p2.join()
# q.put(None)
# q.put(None)
q.join() # 等待队列中所有的数据被取完再往下执行代码
线程
-
进程:资源单位(在内存空间中开辟一块独立的空间)
-
线程:执行单位(代码执行过程,执行代码中所需要使用的资源都找所在的进程索要)
-
每一个进程至少有一个线程
-
进程和线程都是虚拟单位,只是为了更加方便的描述问题
-
开设进程
- 1 申请内存空间 耗资源
- 2 “拷贝代码” 耗资源
-
开设线程
- 一个进程内可以开设多个线程,在同一个进程内开设多个线程无需再申请内存空间
- 同一个进程下的多个线程数据是共享的
开启线程的两种方式
- 方式1
from multiprocessing import Process
from threading import Thread
import time
def task(name):
print('%s is running'%name)
time.sleep(1)
print('%s is over'%name)
t = Thread(target=task, args=('egon',))
t.start()
print('主')
- 方式2
from threading import Thread
import time
class MyThread(Thread):
def __init__(self, name):
# 重写了别人的方法,又不知道别人的方法里有啥,就调用父类的方法
super().__init__()
self.name = name
def run(self):
print('%s is running' %self.name)
time.sleep(1)
print('egon DSB')
if __name__ == '__main__':
t = MyThread('egon')
t.start()
print('主')
tcp服务端实现并发效果
server
import socket
from threading import Thread
from multiprocessing import Process
# 服务端
server = socket.socket() #括号内不加参数,默认就是TCP协议
server.bind(('127.0.0.1', 8080))
server.listen(5)
# 服务代码封装
def talk(conn):
# 通信循环
while True:
try:
data = conn.recv(1024)
if len(data) == 0:
break
print(data.decode('utf-8'))
conn.send(data.upper())
except ConnectionResetError as e:
print(e)
break
conn.close()
# 连接循环
while True:
conn, addr = server.accept()
t = Thread(target=talk, args=(conn,))
t.start()
client
import socket
client = socket.socket()
client.connect(('127.0.0.1', 8080))
while True:
client.send(b'hello world')
data = client.recv(1024)
print(data.decode('utf-8'))
线程对象的join方法
from threading import Thread
import time
def task(name):
print('%s is running' %name)
time.sleep(3)
print('%s is over' %name)
if __name__ == '__main__':
t = Thread(target=task,args=('egon',))
t.start()
t.join() #主线程等待子线程运行结束再执行
print('主')
同一个进程下的多个线程数据是共享的
from threading import Thread
import time
money = 100
def task():
global money
money = 666
if __name__ == '__main__':
t = Thread(target=task)
t.start()
t.join()
print(money)
线程对象属性及其它方法
from threading import Thread, active_count, current_thread
import os, time
def task(n):
# print('hello world', os.getpid())
print('hello world', current_thread().name)
time.sleep(n)
if __name__ == '__main__':
t = Thread(target=task, args=(1,))
t1 = Thread(target=task,args=(2,))
t.start()
t1.start()
t1.join()
print('主', active_count()) # 统计当前正在活跃的线程数
# print('主', os.getpid())
# print('主', current_thread().name) # 获取线程名字
守护线程
- 主线程运行结束之后不会立刻结束,会等待所有其它非守护线程结束才会结束
- 主线程的结束意味着所在的进程的结束
from threading import Thread
import time
def task(name):
print('%s is running' %name)
time.sleep(1)
print('%s is over' %name)
if __name__ == '__main__':
t = Thread(target=task, args=('egon',))
t.daemon = True
t.start()
print('主')
from threading import Thread
from multiprocessing import Process
import time
def foo():
print(123)
time.sleep(1)
print('end123')
def func():
print(456)
time.sleep(3)
print('end456')
if __name__ == '__main__':
t1 = Thread(target=foo)
t2 = Thread(target=func)
t1.daemon = True
t1.start()
t2.start()
print('主......')
线程互斥锁
from threading import Thread, Lock
import time
money = 100
mutex = Lock()
def task():
global money
mutex.acquire()
tmp = money
time.sleep(0.1)
money = tmp - 1
mutex.release()
if __name__ == '__main__':
t_list = []
for i in range(100):
t = Thread(target=task)
t.start()
t_list.append(t)
for t in t_list:
t.join()
print(money)
GIL全局解释器锁
https://www.cnblogs.com/xiaoyuanqujing/protected/articles/11715730.html
'''
定义:
In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple
native threads from executing Python bytecodes at once. This lock is necessary mainly
because CPython’s memory management is not thread-safe. (However, since the GIL
exists, other features have grown to depend on the guarantees that it enforces.)
'''
在Cpython解释器中GIL是一把互斥锁,用来阻止同一个进程下的多个线程的同时执行(同一个进程下的多个线程无法利用多核优势)
因为cpython中的内存管理不是线程安全的
内存管理(垃圾回收机制)
- 应用计数
- 标记清除
- 分代回收
- 1 GIL不是python的特点而是Cpython解释器的特点
- 2 GIL是保证解释器级别的数据安全
- 3 GIL会导致同一个进程下的多个线程无法同时执行
- 4 针对不同的数据还是需要加不同的锁处理
- 5 解释型语言的通病: 同一个进程下多个线程无法利用多核优势
GIL与普通互斥锁的区别
from threading import Thread, Lock
import time
mutex = Lock()
money = 100
def task():
global money
# with mutex:
# tmp = money
# time.sleep(0.1) # 遇到io会释放GIL
# money = tmp - 1
mutex.acquire()
tmp = money
time.sleep(0.1)
money = tmp - 1
mutex.release()
if __name__ == '__main__':
t_list = []
for i in range(100):
t = Thread(target=task)
t.start()
t_list.append(t)
for t in t_list:
t.join()
print(money)
多进程与多线程比较
单核:多个任务(IO密集型/计算密集型)
多核: 多个任务(IO密集型/计算密集型)
- 计算密集型使用多进程
- IO密集型使用多线程
#计算密集型
from multiprocessing import Process
from threading import Thread
import time
import os
def work():
res = 0
for i in range(100000000):
res *= i
if __name__ == '__main__':
l = []
print(os.cpu_count()) # 获取当前计算机CPU核心数
start_time = time.time()
for i in range(8):
# p = Process(target=work) # 9.708976984024048
t = Thread(target=work) # 38.72370767593384
# p.start()
t.start()
# l.append(p)
l.append(t)
for p in l:
p.join()
print(time.time()-start_time)
# IO密集型
from multiprocessing import Process
from threading import Thread
import time
import os
def work():
time.sleep(2)
if __name__ == '__main__':
l = []
print(os.cpu_count()) # 获取当前计算机CPU核心数
start_time = time.time()
for i in range(400):
# p = Process(target=work) # 11.842133283615112
t = Thread(target=work) # 2.0397207736968994
# p.start()
t.start()
# l.append(p)
l.append(t)
for p in l:
p.join()
print(time.time()-start_time)
- 多进程和多线程都有各自的优势
- 通常都是多进程下面开设多线程
死锁与递归锁
死锁:整个程序卡死(阻塞)
死锁
from threading import Thread, Lock
import time
mutexA = Lock()
mutexB = Lock()
# 类只要加括号多次,产生的肯定是不同的对象
# 如果想实现多次加括号得到相同的对象,需要使用单例模式
class MyThead(Thread):
def run(self):
self.func1()
self.func2()
def func1(self):
mutexA.acquire()
print('%s 抢到A锁' %self.name) #获取当前线程名
mutexB.acquire()
print('%s 抢到B锁' %self.name)
mutexB.release()
mutexA.release()
def func2(self):
mutexB.acquire()
print('%s 抢到B锁' % self.name)
time.sleep(2)
mutexA.acquire()
print('%s 抢到A锁' % self.name) # 获取当前线程名
mutexA.release()
mutexB.release()
if __name__ == '__main__':
for i in range(10):
t = MyThead()
t.start()
递归锁
- 可以被连续的acquireh和release
- 但是只能被第一个抢到锁的线程执行此操作
- 它内部有一个计数器, 每acquire一次计数器加一,每release一次计数器减一,只要计数不为零,其它线程都无法抢该锁
from threading import Thread, Lock, RLock
import time
# mutexA = Lock()
# mutexB = Lock()
mutexA = mutexB = RLock()
# 类只要加括号多次,产生的肯定是不同的对象
# 如果想实现多次加括号得到相同的对象,需要使用单例模式
class MyThead(Thread):
def run(self):
self.func1()
self.func2()
def func1(self):
mutexA.acquire()
print('%s 抢到A锁' %self.name) #获取当前线程名
mutexB.acquire()
print('%s 抢到B锁' %self.name)
mutexB.release()
mutexA.release()
def func2(self):
mutexB.acquire()
print('%s 抢到B锁' % self.name)
time.sleep(2)
mutexA.acquire()
print('%s 抢到A锁' % self.name) # 获取当前线程名
mutexA.release()
mutexB.release()
if __name__ == '__main__':
for i in range(10):
t = MyThead()
t.start()
信号量
信号量在不同的阶段对应不同的技术点
在并发编程中信号量指的是锁
from threading import Thread, Semaphore
import time
import random
sm = Semaphore(5) #括号内数字表示锁的数量
def task(name):
sm.acquire()
print('%s 正在蹲坑' %name)
time.sleep(random.randint(1, 5))
sm.release()
if __name__ == '__main__':
for i in range(20):
t = Thread(target=task,args=('伞兵%s号' %i, ))
t.start()
event事件
一些进程/线程需要等待另外一些进程/线程运行完毕之后才能运行,类似于发射信号一样
from threading import Thread, Event
import time
event = Event()
def light():
print('红灯亮着的')
time.sleep(3)
print('绿灯亮了')
# 告诉等待红灯的人可以走了
event.set()
def car(name):
print('%s 车正在等红灯' %name)
event.wait() # 等待别人发消息
print('%s 车加油门走了' %name)
if __name__ == '__main__':
t = Thread(target=light)
t.start()
for i in range(20):
t = Thread(target=car, args=('%s' %i, ))
t.start()
线程q
同一个进程下多个线程数据是共享的
队列是管道+锁 组成的
队列是为了保证数据的安全
队列q 先进先出
import queue
q = queue.Queue(3)
q.put(1)
q.get()
q.get_nowait()
q.get(timeout=3)
q.full()
q.empty()
后进先出q
import queue
q = queue.LifoQueue(3)
q.put(1)
q.put(2)
q.put(3)
print(q.get()) # 3
优先级q
可以给放入队列中的数据设置进出的优先级
import queue
q = queue.PriorityQueue(4)
q.put((10, '111')) # put括号内容放一个元祖 第一个数字表示优先级,数字越小,优先级越高
q.put((100, '222'))
q.put((0, '333'))
q.put((-5, '444'))
print(q.get()) # (-5, '444')
池
- 不可能无限制的开设进程和线程,因为计算机硬件的资源有限
- 保证计算机硬件能够正常工作的情况下最大限度使用
- 池是用来保证计算机硬件安全的情况下最大限度的利用计算机,它降低了程序的运行效率,但是保证了计算机硬件的安全,从而让程序能够正常运行
线程池
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import time
pool = ThreadPoolExecutor(5) # 固定只有5个线程,不会重复创建与销毁
# 括号内可以传数字,不传默认开设当前计算机cpu个数5倍的线程
def task(n):
print(n)
time.sleep(2)
return n**n
# pool.submit(task, 1) # 向池中提交任务, 异步提交
# print('主')
t_list = []
for i in range(20):
res = pool.submit(task, i)
# print(res.result())
t_list.append(res)
# 等待线程池中的所有的任务执行完毕之后再继续往下执行
pool.shutdown() # 关闭线程池,等待线程池中那个所有的任务运行完毕
for t in t_list:
print('>>>', t.result())
进程池
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import time
import os
# pool = ThreadPoolExecutor(5) # 固定只有5个线程,不会重复创建与销毁
# 括号内可以传数字,不传默认开设当前计算机cpu个数5倍的线程
pool = ProcessPoolExecutor(5)
# 括号内可以传数字,不传默认开设当前计算机cpu个数的进程
def task(n):
print(n, os.getpid())
time.sleep(2)
return n**n
def call_back(n):
print('call_back>>>:', n.result())
if __name__ == '__main__':
# pool.submit(task, 1) # 向池中提交任务, 异步提交
# print('主')
t_list = []
for i in range(20):
# res = pool.submit(task, i)
res = pool.submit(task, i).add_done_callback(call_back)
# print(res.result())
# t_list.append(res)
# 等待线程池中的所有的任务执行完毕之后再继续往下执行
# pool.shutdown() # 关闭线程池,等待线程池中那个所有的任务运行完毕
# for t in t_list:
# print('>>>', t.result())
协程
- 进程: 资源单位
- 线程: 执行单位
- 协程: 单线程下实现并发(在代码层面上检测所有的io操作,一旦遇到io,在代码级别完成切换,给CPU的感觉是程序一直运行,没有io,从而提升程序的运行效率)
多道技术: 切换+保存状态
cpu两种切换
1.程序遇到io
2.程序长时间占用
切换: 切换不一定是提升效率,也有可能是降低效率
io切 提升
没有io切 降低
保存状态: 保存上一次执行的状态, 下一次来接着上一次的操作继续往后执行
gevent模块
pip3 install gevent
from gevent import monkey;monkey.patch_all()
import time
from gevent import spawn
def heng():
print('哼')
time.sleep(2)
print('哼')
def ha():
print('哈')
time.sleep(3)
print('哈')
def heiheihei():
print('heiheihei')
time.sleep(5)
print('heiheihei')
start_time = time.time()
g1 = spawn(heng)
g2 = spawn(ha)
g3 = spawn(heiheihei)
g1.join()
g2.join() # 等待被检测的任务执行完毕,再往后继续执行
g3.join()
# heng()
# ha()
print(time.time() - start_time)
协程实现TCP服务端并发
server
from gevent import monkey;monkey.patch_all()
import socket
from gevent import spawn
def communication(conn):
while True:
try:
data = conn.recv(1024)
if len(data) == 0:
break
conn.send(data.upper())
except ConnectionResetError as e:
print(e)
break
conn.close()
def server(ip, port):
server = socket.socket()
server.bind((ip, port))
server.listen(5)
while True:
conn, addr = server.accept()
spawn(communication, conn)
if __name__ == '__main__':
g1 = spawn(server, '127.0.0.1', 8080)
g1.join()
client
from threading import Thread, current_thread
import socket
def x_client():
client = socket.socket()
client.connect(('127.0.0.1', 8080))
n = 0
while True:
msg = '%s say hello %s' %(current_thread().name, n)
n += 1
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print(data.decode('utf-8'))
if __name__ == '__main__':
for i in range(500):
t = Thread(target=x_client)
t.start()
多进程下面开设多线程
多线程下面开设协程
IO模型
- blocking IO 阻塞IO
- nonblocking IO 非阻塞IO
- IO multiplexing IO多路复用
- signal driven IO 信号驱动IO
- asynchronous IO 异步IO
网络阻塞状态
- accept
- recv
- recvfrom
阻塞IO模型
server
import socket
server = socket.socket()
server.bind(('127.0.0.1', 8080))
server.listen(5)
while True:
conn, addr = server.accept()
while True:
try:
data = conn.recv(1024)
if len(data) == 0:
break
print(data)
conn.send(data.upper())
except ConnectionResetError as e:
break
conn.close()
client
import socket
client = socket.socket()
client.connect(('127.0.0.1', 8080))
while True:
client.send(b'hello world')
data = client.recv(1024)
print(data)
非阻塞IO模型
提交之后无论是否有数据,都会立刻获得一个结果
server
import socket
import time
server = socket.socket()
server.bind(('127.0.0.1', 8080))
server.listen(5)
server.setblocking(False) # 将所有的网络阻塞变为非阻塞
r_list = []
del_list = []
while True:
try:
conn, addr = server.accept()
r_list.append(conn)
except BlockingIOError as e:
# time.sleep(0.1)
# print('列表的长度:', len(r_list))
# print('做其他事')
for conn in r_list:
try:
data = conn.recv(1024)
if len(data) == 0: # 客户端断开连接
conn.close() # 关闭conn
# 将无用的conn从r_list删除
del_list.append(conn)
continue
conn.send(data.upper())
except BlockingIOError:
continue
except ConnectionResetError:
conn.close()
del_list.append(conn)
# 回收无用的连接
for conn in del_list:
r_list.remove(conn)
del_list.clear()
client
import socket
client = socket.socket()
client.connect(('127.0.0.1', 8080))
while True:
client.send(b'hello world')
data = client.recv(1024)
print(data)
IO多路复用
监管机制
- select机制 (windows Linux都有)
- poll机制 (只在Linux有)poll监管的数量更多
- epoll机制 (只在Linux有)它给每一个监管对象都绑定一个回调机制,一旦有响应,回调机制立刻发起提醒
selectors模块可以根据不同的操作系统选择相应的监管机制
server
import socket
import select
server = socket.socket()
server.bind(('127.0.0.1', 8080))
server.listen(5)
server.setblocking(False)
read_list = [server]
while True:
r_list, w_list, x_list = select.select(read_list, [], []) # 检测server
# print(r_list)
for i in r_list:
if i is server:
conn, addr = i.accept()
read_list.append(conn)
else:
res = i.recv(1024)
if len(res) == 0:
i.close()
# 将无效的监管对象移除
read_list.remove(i)
continue
print(res)
i.send(b'heiheihei')
client
import socket
client = socket.socket()
client.connect(('127.0.0.1', 8080))
while True:
client.send(b'hello world')
data = client.recv(1024)
print(data)
异步IO模型
相关模块和框架
- asyncio模块
- 异步框架 sanic tornado twisted
import threading
import asyncio
@asyncio.coroutine
def hello():
print('hello world %s' %threading.current_thread())
yield from asyncio.sleep(1) # 换成真正的io操作
print('hello world %s' %threading.current_thread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()