码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-11-18 23:44:25      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:page   range   get   super   pre   print   requests   put   cep   

利用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实现生产者和消费者模式

标签:page   range   get   super   pre   print   requests   put   cep   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!