Python中使用线程进行排队处理任务

由于Python语言本身是没有支持线程池的api,所以我自己看一些教程和文章,自己写了一个demo,直接上码:

#!/usr/bin/evn python

# -*- coding:utf-8 -*-

import threading

import Queue

import time

import contextlib

"""

创建一个线程池对象

"""

class ThreadPool(object):

StopEnevt=object(); #开关的对象

free_thread_list=[] # 空闲线程集合

genenater_thread_list=[] #总线程集合

taskQueue=Queue.Queue();# 任务集合

max_num =10;# 最大的线程数

def __int__(self,max_num=10):

#如果线程池初始化的时候有设置max_num直接替换,如果没有设置,默认是10个线程数。

self.max_num=max_num;

#self.taskQueue=Queue.Queue();

def createThread(self):#创建线程的方法

thread=threading.Thread(target=self.runTask);

thread.start();

def runTask(self):

#获取当前线程的方法

currentThread=threading.currentThread();

#把创建好的线程添加到总的线程。

self.genenater_thread_list.append(currentThread);

event=self.taskQueue.get();

while event!=self.StopEnevt:

func,args,callback=event;

try:

callbackarge = func(*args);

if callback is not None:

if callbackarge is not None:

callback(*callbackarge);

else:

callback();

except Exception as e:

print("e.message:"+str(e.message))

finally:

#self.free_thread_list.append(currentThread)

#event=self.taskQueue.get();

#self.free_thread_list.remove(currentThread);

with threadContext(strelist=self.free_thread_list,val=currentThread):

"""

2.这些代码的是使用与yield联系在一起的

当执行的了strelist.append(val)代码之后

就执行的这个代码

"""

event = self.taskQueue.get();

else:

# 没有任务之后在总的线程集删除当前线程。

self.genenater_thread_list.remove(currentThread);

 

def asynTask(self,func,args=(),callback=None):

task=(func,args,callback);

self.taskQueue.put(task);

# 如果线程没有创建的时候,就要调用创建线程的方法

if len(self.free_thread_list)==0 and len(self.genenater_thread_list)<self.max_num:

self.createThread();

 

def close(self):

# 关闭线程池的

count=len(self.genenater_thread_list)

for i in range(count):

self.taskQueue.put(self.StopEnevt);

self.taskQueue.empty();

 

def testTaskfunc(i):

time.sleep(0.5)

print("testTaskfunc i:"+str(i)+"\n")

 

def testTaskCallBack():

print("this testTaskCallBack func\n")

 

"""

管理上下文的方法

"""

@contextlib.contextmanager

def threadContext(strelist,val):

# 1.上下文中执行的顺序是从上而下,

strelist.append(val)

try:

yield #在这里。

finally:

# 3.这是在执行的了yield的代码之后最后执行。

strelist.remove(val)

 

 

pool=ThreadPool();

for i in range(100):

pool.asynTask(func=testTaskfunc,args=(i,),callback=testTaskCallBack);

 

pool.close();

 

    大家有什么意见可以留言一下!

Python中,可以使用多种库来实现任务队列处理,比如内置的`queue`模块、第三方库如`celery`、`multiprocessing`或`concurrent.futures`等。这里简单介绍几种常见的方法: 1. **`queue`模块**:Python标准库中的`queue`模块提供了一种线程安全的消息传递机制,如`Queue`和`LifoQueue`。你可以创建一个队列,将任务添加到队列中,然后通过消费者线程逐个取出并执行。 ```python from queue import Queue # 创建一个队列 task_queue = Queue() # 添加任务 def add_task(task): task_queue.put(task) # 消费者函数 def consume_task(): while True: task = task_queue.get() # 执行任务 process_task(task) ``` 2. **`concurrent.futures`模块**:这个模块提供了高级接口来异步执行函数,例如`ThreadPoolExecutor`用于基于线程任务队列,`ProcessPoolExecutor`用于进程池。 ```python import concurrent.futures # 创建一个线程池 with concurrent.futures.ThreadPoolExecutor() as executor: future_to_task = {executor.submit(process_task, task): task for task in tasks} for future in concurrent.futures.as_completed(future_to_task): try: task = future_to_task[future] future.result() # 获取结果 except Exception as exc: print('%r generated an exception: %s' % (task, exc)) ``` 3. **第三方库如`Celery`**:适用于复杂的分布式任务管理,适合大规模的生产环境。它利用RabbitMQ、Redis等作为消息中间件,支持异步处理和后台任务。 ```python from celery import Celery app = Celery('tasks', broker='pyamqp://guest@localhost//') @app.task def process_task(task): # 这里是实际处理任务的代码 ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值