python 线程及线程池
一、多线程
import threading
from time import ctime,sleep def music(func):
for i in range(2):
print("I was listening to %s. %s" %(func,ctime()))
sleep(1) def move(func):
for i in range(2):
print("I was at the %s! %s" %(func,ctime()))
sleep(5) threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2) if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start() t.join() print("all over %s" %ctime())
二、线程池(自实现)
'''
线程池的概念就是我们将1000件活,原本由1000个人来做,
现在只分配5个人来做,这5个人就是线程池数,
并且他们处与一直运行状态,除非主程序结束,否则,将不会结束。
''' from queue import Queue
from threading import Thread
import random
import time def person(i,q):
while True: #这个人一直处与可以接活干的状态
q.get()
print("Thread",i,"is doing the job")
time.sleep(random.randint(1,5))#每个人干活的时间不一样,自然就会导致每个人分配的件数不同(这里是干活的地方)
q.task_done() #接到的活做完了,向上汇报 q = Queue() #分配1000件活
for x in range(100):
q.put(x) #叫了5个人去干活
for i in range(5):
worker=Thread(target=person, args=(i,q))
worker.setDaemon(True)
worker.start() q.join() #这5个人把1000件活都做完后,结束.
三、线程池(库实现)
看吧!只用4行代码就搞定了!其中三行还是固定写法。
import requests
from multiprocessing.dummy import Pool as ThreadPool urls = [
'http://www.baidu.com',
'http://www.163.com',
'http://www.sina.cn',
'http://www.live.com',
'http://www.mozila.org',
'http://www.sohu.com',
'http://www.tudou.com',
'http://www.qq.com',
'http://www.taobao.com',
'http://www.alibaba.com',
] # Make the Pool of workers
pool = ThreadPool(4) # 注意此处的 map 函数!!!!
# Open the urls in their own threads
# and return the results
results = pool.map(requests.get, urls) #close the pool and wait for the work to finish
pool.close()
pool.join()
from multiprocessing import Pool def f(x):
return x*x with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
四、如何更加高效(生产、消费者模式)
比起经典的方式来说简单很多,效率高,易懂,而且没什么死锁的陷阱。
from multiprocessing import Pool, Queue
import redis
import requests queue = Queue(20) def consumer():
r = redis.Redis(host='127.0.0.1',port=6379,db=1)
while True:
k, url = r.blpop(['pool',])
queue.put(url) def worker():
while True:
url = queue.get()
print(requests.get(url).text) def process(ptype):
try:
if ptype:
consumer()
else:
worker()
except:
pass pool = Pool(5)
print pool.map(process, [1,0,0,0,0])
pool.close()
pool.join()
python 线程及线程池的更多相关文章
- python爬虫之线程池和进程池
一.需求 最近准备爬取某电商网站的数据,先不考虑代理.分布式,先说效率问题(当然你要是请求的太快就会被封掉,亲测,400个请求过去,服务器直接拒绝连接,心碎),步入正题.一般情况下小白的我们第一个想到 ...
- Python之路——线程池
1 线程基础 1.1 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2 线程同步——锁 多线程的优势在于可以同时运行多个任务(至少感觉起来是这样,其实Python中是伪多线程).但是当线程 ...
- python爬虫14 | 就这么说吧,如果你不懂python多线程和线程池,那就去河边摸鱼!
你知道吗? 在我的心里 你是多么的重要 就像 恩 请允许我来一段 freestyle 你们准备好了妹油 你看 这个碗 它又大又圆 就像 这条面 它又长又宽 你们 在这里 看文章 觉得 很开心 就像 我 ...
- python day 20: 线程池与协程,多进程TCP服务器
目录 python day 20: 线程池与协程 2. 线程 3. 进程 4. 协程:gevent模块,又叫微线程 5. 扩展 6. 自定义线程池 7. 实现多进程TCP服务器 8. 实现多线程TCP ...
- Python中的进程池与线程池(包含代码)
Python中的进程池与线程池 引入进程池与线程池 使用ProcessPoolExecutor进程池,使用ThreadPoolExecutor 使用shutdown 使用submit同步调用 使用su ...
- Python程序中的线程操作(线程池)-concurrent模块
目录 Python程序中的线程操作(线程池)-concurrent模块 一.Python标准模块--concurrent.futures 二.介绍 三.基本方法 四.ProcessPoolExecut ...
- python 并发专题(二):python线程以及线程池相关以及实现
一 多线程实现 线程模块 - 多线程主要的内容:直接进行多线程操作,线程同步,带队列的多线程: Python3 通过两个标准库 _thread 和 threading 提供对线程的支持. _threa ...
- Python爬虫之线程池
详情点我跳转 关注公众号"轻松学编程"了解更多. 一.为什么要使用线程池? 对于任务数量不断增加的程序,每有一个任务就生成一个线程,最终会导致线程数量的失控,例如,整站爬虫,假设初 ...
- python创建一个线程和一个线程池
创建一个线程 1.示例代码 import time import threading def task(arg): time.sleep(2) while True: num = input('> ...
- Python简单的线程池
class ThreadPool(object): def __init__(self, max_num=20): # 创建一个队列,队列里最多只能有10个数据 self.queue = queue. ...
随机推荐
- python modules and packages
https://realpython.com/python-modules-packages/ 在软件开发中,一个module是具有一些相关功能的软件集合,比如,当你在开发一个游戏时,可能会有一个模块 ...
- nginx 的socket 选项处理--TCP_DEFER_ACCEPT
在nginx listen配置项的说明中有一个选项: deferred -- indicates to use that postponed accept(2) on Linux with. the ...
- Linux查看磁盘读写
---------- 查看磁盘读写---------iostat -k 1 SQL> ho iostatLinux 2.6.32-279.el6.x86_64 (server-92) 08/1 ...
- 细说C#继承
简介 继承(封装.多态)是面向对象编程三大特性之一,继承的思想就是摈弃代码的冗余,实现更好的重用性. 继承从字面上理解,无外乎让人想到某人继承某人的某些东西,一个给一个拿.这个语义在生活中,就像 家族 ...
- MySQL慢日志简介及Anemometer工具介绍
作者:王航威 - fordba.com 来源:http://fordba.com/box-anemometer-visual-mysql-slow.html,叶师傅对原文内容略有调整 备注:王航威是知 ...
- 关于Tomcat端口出现的问题
=Several ports (8005, 8080, 8009) required by Tomcat v7.0 Server at localhost are already in use. Th ...
- 跟我一起阅读Java源代码之HashMap(三)
上一节我们讲到了如何用散列和链表实现HashMap,其中有一个疑问今天已经有些答案了,为什么要用链表而不是数组 链表的作用有如下两点好处 1. remove操作时效率高,只维护指针的变化即可,无需进行 ...
- Center OS 7 /etc/rc.d/init.d/network, status=6
service network restart 报错 Center OS 7 /etc/rc.d/init.d/network status=6 google上找到答案: Just in case a ...
- BZOJ2425:[HAOI2010]计数(数位DP)
Description 你有一组非零数字(不一定唯一),你可以在其中插入任意个0,这样就可以产生无限个数.比如说给定{1,2},那么可以生成数字12,21,102,120,201,210,1002,1 ...
- SPOJ-SUBSET Balanced Cow Subsets
嘟嘟嘟spoj 嘟嘟嘟vjudge 嘟嘟嘟luogu 这个数据范围都能想到是折半搜索. 但具体怎么搜呢? 还得扣着方程模型来想:我们把题中的两个相等的集合分别叫做左边和右边,令序列前一半中放到左边的数 ...