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

利用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()

 

转载于:https://www.cnblogs.com/Huangsh2017Come-on/p/7858109.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值