Hugh's Blog

Python 简单实现多线程任务队列

使用队列实现一个简单的多线程任务。 from queue import Queue from threading import Thread class TaskQueue(Queue): def __init__(self, num_workers=1): Queue.__init__(self) self.num_workers = num_workers self.start_workers() def start_workers(self): for _ in range(self.num_workers): t = Thread(target=self.do_task) t.daemon = True t.start() def add_task(self, func, *args, **kwargs): args = args or () kwargs = kwargs or {} self.put((func, args, kwargs)) def do_task(self): while True: ...

 

Python 连接池简单实现

使用队列实现一个简单的连接池。 from queue import Queue class Client(object): def query(self, sql:str): return ['ok'] def disconnect(self): pass class MyClient(object): def __init__(self): self.pool = None self._client = Client() def query(self, sql:str): try: data = self._client.query(sql) except: data = [] if self.pool is not None: self.pool.free(self) return data def disconnect(self): self._client.disconnect() class MyClientPool(object): def __init__(self, max_conns=5, max_timeout=5): self.max_conns = max_conns ...