一、多线程

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. apache2.2+php5.3+mysql5.5+Zend Guard Loader集成包

    由前一篇文章 http://www.cnblogs.com/darktime/p/3407980.html 我就配置了一个环境包,免安装的,只需要运行一个.bat的文件文件就算安装成功了 如果你需要用 ...

  2. sql面试

    1.用一条SQL语句 查询出每门课都大于80分的学生姓名 name   kecheng   fenshu 张三     语文       81张三     数学       75李四     语文   ...

  3. Linux wc命令详解

    wc常见命令参数 wc -l : 统计行 wc -c: 统计字节数 wc -m:统计字符数,不能与-c同时使用 wc -w:统计字数 wc -L:打印最长长度 注意: wc 可以直接后面跟文件使用,但 ...

  4. 基于php-fpm的配置详解

    php5.3自带php-fpm/usr/local/php/etc/php-fpm.confpid = run/php-fpm.pidpid设置,默认在安装目录中的var/run/php-fpm.pi ...

  5. 一键安装lnmp1.5

    系统需求: CentOS/RHEL/Fedora/Debian/Ubuntu/Raspbian/Deepin/Aliyun/Amazon/Mint Linux发行版 需要5GB以上硬盘剩余空间,MyS ...

  6. 【Excel】单元格的下拉框是怎么做的?

    如果我们希望将产品这一列的每个单元格都能选择 左侧的产品就好了,就像这样 这里使用的是"验证数据有效性"功能 在这里: 点击F,选择F列后,打开“数据验证”,如图,选择序列,选择来 ...

  7. 设计一套砝码要求能称量出1 ~ 100g之间的任意重量,请问至少需要多少个砝码?以及每个砝码各自的重量是多少?

    解析: 1g => 1g 2g => 1g 1g => 1 ~ 2g之间的重量 => 1g 2g => 1 ~ 3g之间的重量 4g => 1g 2g 1g =&g ...

  8. November 23rd 2016 Week 48th Wednesday

    I always like walking in the rain, so no one can see me crying. 我一直喜欢在雨中行走,那样就没人能看到我的眼泪. I like walk ...

  9. 简单的dp加贪心

    题目链接:传送门 这个题目让我纠结了好久,之后恍然大悟是求最长的递减序列,并加上贪心的算法,如果有大于两个的发射系统,应该判断使导弹的高度与此时个个发射系统的高度比较,选取高度差最小的去执行这次的拦截 ...

  10. PHP设计模式系列 - 委托模式

    委托模式 通过分配或委托其他对象,委托设计模式能够去除核心对象中的判决和复杂的功能性. 应用场景 设计了一个cd类,类中有mp3播放模式,和mp4播放模式 改进前,使用cd类的播放模式,需要在实例化的 ...