Python--day38---进程间通信--队列和管道(multiprocess.Queue、multiprocess.Pipe)

初识队列:

进程间通信IPC(Inter-Process Communication)

1,队列的方法:

q = Queue(5)
1,q.put(1)    #把1放进队列

2,print(q.full()) #队列是否满了

3,print(q.empty()) #队列是否为空

4,q.get_nowait()  #队列为空则抛异常

 1 #队列 先进先出
 2 #IPC
 3 import time
 4 from multiprocessing import Queue
 5 q = Queue(5)
 6 q.put(1)
 7 q.put(2)
 8 q.put(3)
 9 q.put(4)
10 q.put(5)
11 print(q.full()) #队列是否满了
12 print(q.get())
13 print(q.get())
14 print(q.get())
15 print(q.get())
16 print(q.get())
17 print(q.empty())    #队列是否为空
18 #while True这个行为非常地耗内存
19 while True:
20     try:
21         q.get_nowait()
22     except:
23         print('队列已空')
24         time.sleep(1)

运行结果:

2,一个例子:

 1 from multiprocessing import Queue,Process
 2 
 3 def produce(q):
 4     q.put('hello')
 5 
 6 def consume(q):
 7     print(q.get())
 8 
 9 if __name__ == '__main__':
10     q = Queue()
11     p = Process(target=produce,args=(q,))
12     p.start()
13     c = Process(target=consume, args=(q,))
14     c.start()
15     

运行结果:

猜你喜欢

转载自www.cnblogs.com/xudj/p/10324151.html