首页 > 编程语言 > 详细

python实现生产者和消费者模式

时间:2017-11-18 23:20:17      阅读:294      评论:0      收藏:0      [点我收藏+]

利用python的线程实现简单生产者和消费者模式,这种模式在多线程编程时还是用的比较多吧,下面是源代码:

 

 1 #!/usr/bin/python
 2 # -*- coding: utf-8 -*-
 3 import requests,time
 4 import threading,queue
 5 
 6 
 7 class mythread_1(threading.Thread):
 8     def __init__(self,queue):
 9         super(mythread_1,self).__init__()
10         self.queue = queue
11     def run(self):
12         try:
13             for i in range(5):
14                 products = http://www.mzitu.com/xinggan/page/+str(i)
15                 self.queue.put(products)
16                 time.sleep(1)
17             print(self.getName(),shengcan finish)
18         except:
19             print(field)
20         finally:
21             print(ok)
22 
23 class mythread_2(threading.Thread):
24     def __init__(self,queue):
25         super(mythread_2,self).__init__()
26         self.queue = queue
27 
28     def run(self):
29         try:
30             for i in range(5):
31                 url = self.queue.get()
32                 reponse = requests.get(url)
33                 print(reponse.status_code)
34                 time.sleep(1)
35             print(self.getName(),xiaofei finish)
36         except:
37             print(field)
38         finally:
39             print(ok)
40 def main():
41     q = queue.Queue()
42     t1 = mythread_1(q)
43     t2 = mythread_2(q)
44     t1.start()
45     t2.start()
46 
47     t1.join()
48     t2.join()

 

python实现生产者和消费者模式

原文:http://www.cnblogs.com/Huangsh2017Come-on/p/7858109.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!