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

 

目录
相关文章
|
Kubernetes Java 测试技术
SpringBoot配置升级,旧的已过时,新的人未知
SpringBoot配置升级,旧的已过时,新的人未知
771 0
|
1天前
|
云安全 人工智能 自然语言处理
|
6天前
|
搜索推荐 编译器 Linux
一个可用于企业开发及通用跨平台的Makefile文件
一款适用于企业级开发的通用跨平台Makefile,支持C/C++混合编译、多目标输出(可执行文件、静态/动态库)、Release/Debug版本管理。配置简洁,仅需修改带`MF_CONFIGURE_`前缀的变量,支持脚本化配置与子Makefile管理,具备完善日志、错误提示和跨平台兼容性,附详细文档与示例,便于学习与集成。
314 116
|
8天前
|
数据采集 人工智能 自然语言处理
Meta SAM3开源:让图像分割,听懂你的话
Meta发布并开源SAM 3,首个支持文本或视觉提示的统一图像视频分割模型,可精准分割“红色条纹伞”等开放词汇概念,覆盖400万独特概念,性能达人类水平75%–80%,推动视觉分割新突破。
600 53
Meta SAM3开源:让图像分割,听懂你的话
|
21天前
|
域名解析 人工智能
【实操攻略】手把手教学,免费领取.CN域名
即日起至2025年12月31日,购买万小智AI建站或云·企业官网,每单可免费领1个.CN域名首年!跟我了解领取攻略吧~
|
5天前
|
人工智能 Java API
Java 正式进入 Agentic AI 时代:Spring AI Alibaba 1.1 发布背后的技术演进
Spring AI Alibaba 1.1 正式发布,提供极简方式构建企业级AI智能体。基于ReactAgent核心,支持多智能体协作、上下文工程与生产级管控,助力开发者快速打造可靠、可扩展的智能应用。
|
4天前
|
弹性计算 人工智能 Cloud Native
阿里云无门槛和有门槛优惠券解析:学生券,满减券,补贴券等优惠券领取与使用介绍
为了回馈用户与助力更多用户节省上云成本,阿里云会经常推出各种优惠券相关的活动,包括无门槛优惠券和有门槛优惠券。本文将详细介绍阿里云无门槛优惠券的领取与使用方式,同时也会概述几种常见的有门槛优惠券,帮助用户更好地利用这些优惠,降低云服务的成本。
268 132
|
8天前
|
机器学习/深度学习 人工智能 自然语言处理
AgentEvolver:让智能体系统学会「自我进化」
AgentEvolver 是一个自进化智能体系统,通过自我任务生成、经验导航与反思归因三大机制,推动AI从“被动执行”迈向“主动学习”。它显著提升强化学习效率,在更少参数下实现更强性能,助力智能体持续自我迭代。开源地址:https://github.com/modelscope/AgentEvolver
415 29