目录
一、队列
二、生产者消费者模型
三、协程
四、selectpollepoll
五、paramiko
六、mysql API调用
一、队列(queue)
队列分以下三种:
class queue.Queue(maxsize=0) #先入先出
class queue.LifoQueue(maxsize=0) #last in fisrt out
class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列
代码如下:
import queue class Foo(object): def __init__(self,n): self.n = n #先进先出 q = queue.Queue(maxsize=3) # q.get(timeout=3) #当队列为空时,get值会阻塞,加timeout参数后,会报错 # q.get_nowait() #与上面一样的效果 q.put([1,2,3]) q.put(Foo(1)) data = q.get_nowait() data2 = q.get_nowait() print(data,type(data)) print(data2,type(data2)) #输出结果 # [1, 2, 3] <class 'list'> # <__main__.Foo object at 0x000001E060337278> <class '__main__.Foo'> print("-----------------") print(q.full()) #判断队列里数据是否满了,满为True,未满为False。 print(q.qsize())#查看现在队列的大小(队列中有多少个数据) print(q.empty())#判断队列是否为空 print("---------------") #先入后出 q = queue.LifoQueue(maxsize=3) q.put(1) q.put(2) q.put(3) print(q.get_nowait()) print(q.get_nowait()) print(q.get_nowait()) #输出结果 # 3 # 2 # 1 print("---------------") #可设施优先级的队列 q = queue.PriorityQueue(maxsize=5) q.put((15,1)) q.put((5,2)) q.put((7,3)) q.put((1,[1,2,3])) print(q.get()) print(q.get()) print(q.get()) print(q.get()) #输出结果 # (1, [1, 2, 3]) # (5, 2) # (7, 3) # (15, 1)
二、生产者消费者模型
import queue,threading import time,random q = queue.Queue() def producer(name): count = 0 while q.qsize() < 20: time.sleep(random.randrange(4)) q.put(count) print("producer %s has produced %s baozi.." %(name,q.qsize())) count += 1 def consumer(name): count = 0 while count <20: time.sleep(random.randrange(3)) if not q.empty(): data2 = q.get_nowait() print('