一、多线程

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. HDFS pipeline写 -- datanode

    站在DataNode的视角,看看pipeline写的流程,本文不分析客户端部分,从客户端写数据之前拿到了3个可写的block位置说起. 每个datanode会创建一个线程DataXceiverServ ...

  2. DES加密(支持ARC与MRC)

    DES加密(支持ARC与MRC) 源文件: YXCrypto.h 与 YXCrypto.m // // YXCrypto.h // 用秘钥给字符串加密或者解密 // // Created by You ...

  3. 使用keychain永久存储数据

    使用keychain永久存储数据 https://github.com/soffes/sskeychain keychain当然还是使用开源的好:),keychain是干啥用的?这个,baidu一下你 ...

  4. IE漏洞的调试心得

    在调试漏洞的过程中,个人感觉最棘手的就是ie浏览器的漏洞和flash player的漏洞了.这里打算记录一下学习过程中的心得(主要是基于uaf类),以方便新人学习. 首先,ie漏洞与众不同的是,程序的 ...

  5. handsontable 和 echarts都定义了require方法,初始化时冲突了,怎么办?

    echarts初始化时报这个错误. require.config is not a function  方案一: 让其中一方的初始化不依赖于 require即可 1.去掉 var testDrowEc ...

  6. C++ new和delete重载

    C++ new和delete重载 2012-02-15 23:25:33|  分类: C/C++|举报|字号 订阅           首先,new和delete是运算符,重载new和delete是可 ...

  7. "函中函" -------------------- func2(func) -------------- 函数名可以当做函数的参数

    def func(): print("吃了么")def func2(fn): print("我是func2") fn() # 执⾏传递过来的fn # 即 fn替 ...

  8. 字符串,元组,列表; 切片&range

    总结:字符串: "" 组成元组: () 组成列表: [] 组成 切片 中括号冒号: [5: 0: -2] # print(s2[5:0:-2]) 此步长为-2,则从右往左取, 则a ...

  9. JVM内存区域划分Eden Space、Survivor Space、Tenured Gen,Perm Gen解释 (生动形象)

    [转自]:https://blog.csdn.net/sd4015700/article/details/50109939 jvm区域总体分两类,heap区和非heap区.heap区又分:Eden S ...

  10. 20165318 《Java程序设计》实验一(Java开发环境的熟悉)实验报告

    20165318 <Java程序设计>实验一(Java开发环境的熟悉)实验报告 一.实验报告封面 课程:Java程序设计        班级:1653班        姓名:孙晓暄    ...