zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    文本查询程序再探
    第15章 面向对象程序设计
    错误和异常处理 使用模板
    PHP会话管理
    身份验证
    表单提交与接收 文件提交与接收
    PHP文件访问
    PHP面向对象
    PHP速学
    第14章 重载运算与类型转换
  • 原文地址:https://www.cnblogs.com/Huangsh2017Come-on/p/7858109.html
Copyright © 2011-2022 走看看