一、多线程

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. ExpressRoute 合作伙伴和对等位置

    本文中的表格提供有关 ExpressRoute 连接提供商.ExpressRoute 地理覆盖范围.通过 ExpressRoute 支持的 Azure 服务以及 ExpressRoute 系统集成商 ...

  2. C# Redis的操作

    Nuget添加StackExchange.Redis的引用 由于Redis封装类同时使用了Json,需要添加JSON.NET引用(Newtonsoft.Json) Redis封装类 /// <s ...

  3. [翻译] TGLStackedViewController

    TGLStackedViewController A stack layout with gesture-based reordering using UICollectionView -- insp ...

  4. SpringBoot+MyBatis连接数据库

    SpringBoot通过MyBatis连接数据库有2种方法: 1.注解 2.XML文件 1.注解 1.构建项目 2.添加依赖: <dependencies> <dependency& ...

  5. HashMap集合特点

      >HashMap集合特点 HashMap:是基于哈希表的Map接口实现. 哈希表的作用是用来保证键的唯一性的.          不明白,直接看HashMap的put方法源码 //HashM ...

  6. Scala编写的打印乘法口诀和金字塔

       刚开始接触scala,觉得语法简单,一时兴起就写了两个简单的例子 public class Calculate { public static void test1(){ for(int i=1 ...

  7. Python time.md

    time模块 Comparing Clocks time.clock():在Unix 上,返回当前的处理器时间,以浮点数秒数表示. time.monotonic():返回一个单调时钟的值(在分秒内), ...

  8. python第二十课——math模块中常用的函数

    属性: e:自然数 pi:圆周率 函数: ceil():向上取整 floor():向下取整 sqrt():开平方根 radians():角度转弧度 degrees():弧度转角度 import mat ...

  9. 2.3 Python语言基础

    2.3 Python语言基础 1 语言语义(Language Semantics) 缩进,而不是括号 Python使用空格(tabs or spaces)来组织代码结构,而不是像R,C++,Java那 ...

  10. Day13 泛型

    泛型 泛型定义 在一个类型(类,接口,方法)之后,定义一个类型参数. 原生类型:类型后面没有指定具体的类型参数. 好处 使用泛型的好处在于,它在编译的时候进行类型安全检查,并且在运行时所有的转换都是强 ...