Python 爬虫实战(4)
2018-01-01 13:30
357 查看
Python 爬虫实战(4)
Dec 22, 2017 | 爬虫文章目录Python 爬虫实战4
个人代码
别人家的代码滑稽
多线程
待添加 条件变量 condition
个人代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #生产者消费者 import threading # , _thread ()python2x是thread import time import queue #python2x是Queue import random mutex = threading.Lock() #等价于_thread.allocate_lock(),也等价于_thread.allocate() myq = queue.Queue(10) num = range(10) class Producer(threading.Thread): def run(self): global myq, num for i in range(30): time.sleep(0.3) if not myq.full() and mutex.acquire(): info = random.choice(num) myq.put(info) print("put in data: ", info, "; queue size", myq.qsize()) mutex.release() class Consumer(threading.Thread): def run(self): global myq, num for i in range(30): time.sleep(1) if not myq.empty() and mutex.acquire(): info = myq.get() print("get out data: ", info, "; queue size", myq.qsize()) mutex.release() def main(): print ('main') p = Producer() c = Consumer() p.start() c.start() if __name__ == '__main__': main() |
别人家的代码【滑稽】:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 4142 | #!/usr/bin/env python # -*- coding:utf-8 -*- import thread, threading import urllib2 import time, random import Queue share_queue = Queue.Queue() #共享队列 my_lock = thread.allocate_lock() class Producer(threading.Thread) : def run(self) : products = range(5) global share_queue while True : num = random.choice(products) my_lock.acquire() share_queue.put(num) print "Produce : ", num my_lock.release() time.sleep(random.random()) class Consumer(threading.Thread) : def run(self) : global share_queue while True: my_lock.acquire() if share_queue.empty() : #这里没有使用信号量机制进行阻塞等待, print "Queue is Empty..." my_lock.release() time.sleep(random.random()) continue num = share_queue.get() print "Consumer : ", num my_lock.release() time.sleep(random.random()) def main() : producer = Producer() consumer = Consumer() producer.start() consumer.start() if __name__ == '__main__': main() |
个人博客 欢迎来访: http://blog.zj2626.com
相关文章推荐
- 大数据实战课程第一季Python基础和网络爬虫数据分析
- 【实战\聚焦Python分布式爬虫必学框架Scrapy 打造搜索引擎项目笔记】第4章 scrapy爬取知名技术文章网站(1)
- Python实战:Python爬虫学习教程,获取电影排行榜
- python3--爬虫实战一:爬取豆瓣电影250
- 【极客学院】-python学习笔记-4-单线程爬虫 (提交表单抓取信息,实战练习)
- Python爬虫实战一之爬取糗事百科段子
- python爬虫实战 - 糗事百科数据的爬取
- Python爬虫实战(八):爬取电影天堂的电影下载链接
- python3 [爬虫入门实战]scrapy爬取盘多多五百万数据并存mongoDB
- Python爬虫实战一 | 抓取取校花网的所有妹子
- 自学Python九 爬虫实战二(美图福利)
- python3爬虫 - cookie登录实战
- Python爬虫实战(动态网页)
- Python爬虫实战六之抓取爱问知识人问题并保存至数据库
- python爬虫实战(七)--------伯乐在线文章(模版)
- Python爬虫实战之爬取链家广州房价_01简单的单页爬虫
- [Python实战项目] - xpath 爬虫实战,获取纵横小说网连载小说最新章节(一)
- Python3 大型网络爬虫实战 — 给 scrapy 爬虫项目设置为防反爬
- Python爬虫实战——豆瓣新书速递
- Python3爬虫实战之爬取京东图书图片