一、多线程

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 线程及线程池的更多相关文章

  1. python爬虫之线程池和进程池

    一.需求 最近准备爬取某电商网站的数据,先不考虑代理.分布式,先说效率问题(当然你要是请求的太快就会被封掉,亲测,400个请求过去,服务器直接拒绝连接,心碎),步入正题.一般情况下小白的我们第一个想到 ...

  2. Python之路——线程池

    1 线程基础 1.1 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2 线程同步——锁 多线程的优势在于可以同时运行多个任务(至少感觉起来是这样,其实Python中是伪多线程).但是当线程 ...

  3. python爬虫14 | 就这么说吧,如果你不懂python多线程和线程池,那就去河边摸鱼!

    你知道吗? 在我的心里 你是多么的重要 就像 恩 请允许我来一段 freestyle 你们准备好了妹油 你看 这个碗 它又大又圆 就像 这条面 它又长又宽 你们 在这里 看文章 觉得 很开心 就像 我 ...

  4. python day 20: 线程池与协程,多进程TCP服务器

    目录 python day 20: 线程池与协程 2. 线程 3. 进程 4. 协程:gevent模块,又叫微线程 5. 扩展 6. 自定义线程池 7. 实现多进程TCP服务器 8. 实现多线程TCP ...

  5. Python中的进程池与线程池(包含代码)

    Python中的进程池与线程池 引入进程池与线程池 使用ProcessPoolExecutor进程池,使用ThreadPoolExecutor 使用shutdown 使用submit同步调用 使用su ...

  6. Python程序中的线程操作(线程池)-concurrent模块

    目录 Python程序中的线程操作(线程池)-concurrent模块 一.Python标准模块--concurrent.futures 二.介绍 三.基本方法 四.ProcessPoolExecut ...

  7. python 并发专题(二):python线程以及线程池相关以及实现

    一 多线程实现 线程模块 - 多线程主要的内容:直接进行多线程操作,线程同步,带队列的多线程: Python3 通过两个标准库 _thread 和 threading 提供对线程的支持. _threa ...

  8. Python爬虫之线程池

    详情点我跳转 关注公众号"轻松学编程"了解更多. 一.为什么要使用线程池? 对于任务数量不断增加的程序,每有一个任务就生成一个线程,最终会导致线程数量的失控,例如,整站爬虫,假设初 ...

  9. python创建一个线程和一个线程池

    创建一个线程 1.示例代码 import time import threading def task(arg): time.sleep(2) while True: num = input('> ...

  10. Python简单的线程池

    class ThreadPool(object): def __init__(self, max_num=20): # 创建一个队列,队列里最多只能有10个数据 self.queue = queue. ...

随机推荐

  1. Skype for Business Server-呼叫质量仪表板(一)安装与配置

    第一篇:安装与配置 很多公司在运行过程中都遇到了难以追踪客服人员绩效的情况,公司没有有效的方法追踪员工在通过电话等远程方式解决客户问题.销售产品.客户关怀的情况.Skype for Business提 ...

  2. SharePoint 2007——内容管理之归档篇

    如果需要使用这个功能普通的站点上(没有使用Record Center站点模板的站点),必须激活'Office SharePoint Server Publishing’  featue. 在使用Rec ...

  3. December 02nd 2016 Week 49th Friday

    People will fall for its appearance while driving passionately. 观者倾心,驭者动魄. An advertisement of Merce ...

  4. php请求页面将返回的页面发送email

    <?php require_once 'CLI_config.php'; require_once dirname(__FILE__).'/../../../../common/framewor ...

  5. ZT 人生真的是一场马拉松吗?

    中国合伙人:孟晓俊:生活应该是什么样的?自己提出的问题应该由自己来回答,别人的回答是别人的答案,是别人的生活,而你应该过自己的生活,不是别人的生活.     人生真的是一场马拉松吗? 投递人 itwr ...

  6. 什么是SEO服务,企业为什么要做SEO?

    SEO服务: 1. 网站提交服务 网站提交是非常重要的,尤其是英文网站(英文网站可以提交到世界各国比较出色的搜索引擎).网站的提交,增加了潜在客户找到网站的机会.网站的提交是一个不断更新的过程,因为搜 ...

  7. 【原创】python requests 库底层Sockets处于close_wait状态

    以前对于Requests库只是简单是使用,在现在公司的后台中,有多个接口是直接使用requests.get .post之类的方法来做的,进行过一段时间的压力测试,发现性能低的可怜,且linux服务器有 ...

  8. [转]HBase高可用性的新阶段

    From:http://m.csdn.net/article_pt.html?arcid=2823943 Apache HBase是一个面向线上服务的数据库,其原生支持Hadoop的特性,使其成为那些 ...

  9. Day10 上传和下载

    上传 将本地文件传输到服务器 jsp:  文件上传的请求方式必须是post  input的type必须是file  enctype="multipart/form-data" ...

  10. JS 兼容大全

    //获取浏览器可视区宽度 function getWidth() { if (window.innerWidth){ return window.innerWidth; } else{ if (doc ...