[Google]生产者 消费者

本博客致力于方便 程序员 交流 各类程序问题   主要是笔试面试题目 及经验), 参与方式: 

各位请投稿到  hackjobswww@gmail.com  , 标题参考格式:   

   xxx大学  - xxx公司 


xxx 大学 : 投稿人 母校 ; 

xxx公司: 投稿人 应聘的公司  


正文写清楚 题目即可 ; ( 如果能附上自己对题目的理解和答案,更好) 


接收到投稿以后,有两个动作: 

 1) 公布在 本blog 上 ; 

  2)邀请加入到一个  专门的讨论组,方便后续的讨论,互相学习,提高 

当然可以,以下是一个简单的生产者消费者模式的多线程下载程序的Python代码: ```python import threading import queue import requests class Downloader: def __init__(self, url_queue, result_queue): self.url_queue = url_queue self.result_queue = result_queue def download(self): while True: url = self.url_queue.get() try: response = requests.get(url) self.result_queue.put(response.content) except Exception as e: print(f"Error downloading {url}: {e}") finally: self.url_queue.task_done() class Producer: def __init__(self, url_queue, urls): self.url_queue = url_queue self.urls = urls def produce(self): for url in self.urls: self.url_queue.put(url) def main(): urls = [ "https://www.example.com", "https://www.google.com", "https://www.python.org", "https://www.github.com", "https://www.stackoverflow.com" ] url_queue = queue.Queue() result_queue = queue.Queue() downloader = Downloader(url_queue, result_queue) downloader_threads = [threading.Thread(target=downloader.download) for _ in range(4)] producer = Producer(url_queue, urls) producer_thread = threading.Thread(target=producer.produce) producer_thread.start() for downloader_thread in downloader_threads: downloader_thread.start() url_queue.join() while not result_queue.empty(): result = result_queue.get() print(len(result)) if __name__ == "__main__": main() ``` 这个程序使用了Python的queue模块来实现生产者消费者模式,其中Downloader类是消费者,Producer类是生产者。程序首先创建了一个包含多个URL的列表,然后创建了一个URL队列和一个结果队列。接着创建了一个Downloader实例和多个Downloader线程,以及一个Producer实例和一个Producer线程。Producer线程将URLs放入URL队列中,Downloader线程从URL队列中取出URL并下载对应的内容,将结果放入结果队列中。最后程序等待URL队列中的所有URL都被处理完毕,然后从结果队列中取出结果并打印结果的长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值