线程间通信--共享变量和Queue
作者:互联网
1.线程通信方式--共享变量
缺点,共享变量需要加锁,来达到我们想要的效果
#!/user/bin/env python # -*- coding:utf-8 -*- # 对于io操作来说,多线程和多进程性能差别不大 # 1.通过Thread类实例化 import time import threading detail_url_list = [] def get_detail_html(detail_url_list): # 使用共享变量 # global detail_url_list while True: if len(detail_url_list): url = detail_url_list.pop() # 爬取文章详情页 print('get detail html started') time.sleep(2) print('get detail html end') def get_detail_url(detail_url_list): while True: # 使用共享变量 # global detail_url_list # 爬取文章列表页 print('get detail url started') time.sleep(2) for i in range(20): detail_url_list.append('http://projectsedu.com/{id}'.format(id=i)) print('get detail url end') # 1.线程通信方式-共享变量 if __name__ == '__main__': start_time = time.time() thread_detail_url = threading.Thread(target=get_detail_url, args=(detail_url_list,)) thread_detail_url.start() for i in range(10): thread_detail_html = threading.Thread(target=get_detail_html, args=(detail_url_list,)) thread_detail_html.start() print('last time: {}'.format(time.time() - start_time))
ps:不要去尝试去运行,我设置了while循环,而且没有设置守护线程。。。
2.通过queue的方式进行线程间的通信
#!/user/bin/env python # -*- coding:utf-8 -*- # 2.通过queue的方式进行线程间的通信 from queue import Queue import time import threading detail_url_list = [] def get_detail_html(queue): while True: # 队列的get方法是一个阻塞的函数,即如果队列为空,就阻塞 url = queue.get() # 爬取文章详情页 print('get detail html started') time.sleep(2) print('get detail html end') def get_detail_url(queue): while True: # 爬取文章列表页 print('get detail url started') time.sleep(2) for i in range(20): # 向队列里面插入数据 # put也是一个阻塞函数,当队列已满的时候,会阻塞 queue.put('http://projectsedu.com/{id}'.format(id=i)) print('get detail url end') # 1.线程通信方式-共享变量 if __name__ == '__main__': # 最好设置一个最大值,不然太大了,回对内存有影响 detail_url_queue = Queue(maxsize=1000) start_time = time.time() thread_detail_url = threading.Thread(target=get_detail_url, args=(detail_url_queue,)) thread_detail_url.start() for i in range(10): thread_detail_html = threading.Thread(target=get_detail_html, args=(detail_url_queue,)) thread_detail_html.start() print('last time: {}'.format(time.time() - start_time))
标签:Queue,get,--,list,detail,间通信,url,html,time 来源: https://www.cnblogs.com/mengdie1978/p/16671359.html