python 线程及线程池

简介: 一、多线程 import threading from time import ctime,sleep def music(func): for i in range(2): print("I was listening to %s.

 

一、多线程

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()

 

目录
相关文章
|
10月前
|
Java Python
写一个python基于线程池的多线程
写一个python基于线程池的多线程
69 9
|
Python
Python的线程01 认识线程
正式的Python专栏第41篇,同学站住,别错过这个从0开始的文章!
158 0
Python的线程01 认识线程
|
10月前
|
监控 数据可视化 Java
Python中的线程池与进程池
【5月更文挑战第19天】本文探讨Python中提高程序性能的关键——线程池和进程池。线程池与进程池是并行编程工具,有效利用多核处理器,加速程序执行。线程是运算调度单位,进程是资源分配和调度基础。线程池与进程池管理线程和进程,减少创建销毁开销。
89 0
|
10月前
|
分布式计算 并行计算 Java
浅析Python自带的线程池和进程池
浅析Python自带的线程池和进程池
580 0
|
1月前
|
Python
python3多线程中使用线程睡眠
本文详细介绍了Python3多线程编程中使用线程睡眠的基本方法和应用场景。通过 `time.sleep()`函数,可以使线程暂停执行一段指定的时间,从而控制线程的执行节奏。通过实际示例演示了如何在多线程中使用线程睡眠来实现计数器和下载器功能。希望本文能帮助您更好地理解和应用Python多线程编程,提高程序的并发能力和执行效率。
59 20
|
7月前
|
调度 Python
|
Java Python
第11天续,Python并发编程之线程池/进程池
@(python) 目录 引言 Executor和Future 使用submit来操作线程池/进程池 add_done_callback实现回调函数 引言 Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要编写自己的线程池/进程池,以空间换时间。
1335 0