q.qsize() 返回队列的大小
q.empty() 如果队列为空,返回True,反之False
q.full() 如果队列满了,返回True,反之False
q.get_nowait() 相当q.get(id, False) 非阻塞
q.put(item) 写入队列
q.put_nowait(item) 相当q.put(item, False)
q.task_done() 在完成一项工作之后 函数向任务已经完成的队列发送一个信号
q.join() 实际上意味着等到队列为空,再执行别的操作
import queue
d=queue.Queue(2) # 可进入的最大个数为2
d.put('12',0) # 加入第一个元素
d.put('34',1) # 加入第二个阻塞
d.put('56',2) # 加入超出时阻塞
d.get(0) # 12
print(d.get(0)) # 34
多进程
进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配的基本单位,是操作系统结构的基础。在早期面向进程设计的计算机结构中,进程是程序的基本执行实体;在当代面向线程设计的计算机结构中,进程是线程的容器。程序是指令、数据及其组织形式的描述,进程是程序的实体。
from multiprocessing import Process
import time
def f(name):
print('hello', name, time.ctime( ))
time.sleep(1)
if __name__ == '__main__':
p_list = [ ]
for i in range(3):
p = Process(target=f, args=('alvin',))
p_list.append(p)
p.start( )
for i in p_list:
p.join( )
print('end')
from multiprocessing import Process
import os
import time
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid()) # 父进程号
print('process id:', os.getpid()) # 本进程号
if __name__ == '__main__':
info('\033[32;1mmain process line\033[0m') # 设置格式
time.sleep(1)
p = Process(target=info, args=('bob',)) # 父进程号直接调用info的进程号
p.start()
p.join()
结果为:
main process line
module name: __main__
parent process: 7716
process id: 2476
bob
module name: __mp_main__
parent process: 2476
process id: 11872
不同进程间内存是不共享的,要想实现两个进程间的数据交换,可以用以下方法:queue
from multiprocessing import Process, Queue
def f(q,n):
q.put([42, n, 'hello'])
if __name__ == '__main__':
q = Queue() # 初始化队列
p_list=[] # 初始化列表
for i in range(3):
p = Process(target=f, args=(q,i))
p_list.append(p)
p.start()
print(q.get())
for i in p_list:
i.join()
pipe
from multiprocessing import Process, Pipe
def f(conn):
conn.send([ 42, None, 'hello' ])
conn.close( )
if __name__ == '__main__':
parent_conn, child_conn = Pipe( )
p = Process(target=f, args=(child_conn,)) # child写入
p.start( )
print(parent_conn.recv( )) # parent_conn读取 [42, None, 'hello']
p.join( )
Manager
from multiprocessing import Process, Manager
def f(d, l,n):
d[n] = '1'
d['2'] = 2
d[0.25] = None
l.append(n)
if __name__ == '__main__':
with Manager() as manager:
d = manager.dict()
l = manager.list(range(5)) # [0, 1, 2, 3, 4]
p_list = []
for i in range(3):
p = Process(target=f, args=(d, l,i))
p.start()
p_list.append(p)
for res in p_list:
res.join()
print(d) # {0: '1', '2': 2, 0.25: None, 1: '1', 2: '1'}
print(l) # [0, 1, 2, 3, 4, 0, 1, 2]
进程加锁
from multiprocessing import Process, Lock
def f(l, i):
l.acquire()
try:
print('hello world', i)
finally:
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f, args=(lock, num)).start()
协程
- 协程,又称微线程,纤程。英文名Coroutine。
- 协程是一种用户态的轻量级线程。
- 协程拥有自己的寄存器上下文和栈。协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈。因此:协程能保留上一次调用时的状态(即所有局部状态的一个特定组合),每次过程重入时,就相当于进入上一次调用的状态, 换种说法:进入上一次离开时所处逻辑流的位置。
协程的好处
- 无需线程上下文切换的开销
- 无需原子操作锁定及同步的开销 “原子操作(atomic operation)是不需要synchronized”,所谓原子操作是指不会被线程调度机制打断的操作;这种操作一旦开始,就一直运行到结束,中间不会有任何 context switch(切换到另一个线程)。原子操作可以是一个步骤,也可以是多个操作步骤,但是其顺序是不可以被打乱,或者切割掉只执行部分。视作整体是原子性的核心。方便切换控制流,简化编程模型。
- 高并发+高扩展性+低成本:一个CPU支持上万的协程都不是问题。所以很适合用于高并发处理。
缺点:
- 无法利用多核资源:协程的本质是个单线程,它不能同时将单个CPU的多个核用上,协程需要和进程配合才能运行在多CPU上.
- 和多进程配合进行阻塞(Blocking)操作(如IO时)会阻塞掉整个程序
yield支持协程
def consumer(name): # 生成器
print("--->starting ...")
while True:
new_baozi = yield
print("[%s] is eating baozi %s" % (name,new_baozi))
def producer():
next(con) # 执行到 yield
next(con2) # 执行到 yield
n = 0
while n < 6:
n +=1
print("\033[32;1m[producer]\033[0m is making baozi %s" % n)
con.send(n) # 从new_baozi =开始往下执行
con2.send(n)
if __name__ == '__main__':
con = consumer("c1") # 创建生成器对象
con2 = consumer("c2")
p = producer() # 执行函数,p为函数返回值