Python实现线程池代码分享
作者:junjie 时间:2021-09-24 18:13:43
原理:建立一个任务队列,然多个线程都从这个任务队列中取出任务然后执行,当然任务队列要加锁,详细请看代码
import threading
import time
import signal
import os
class task_info(object):
def __init__(self):
self.func = None
self.parm0 = None
self.parm1 = None
self.parm2 = None
class task_list(object):
def __init__(self):
self.tl = []
self.mutex = threading.Lock()
self.sem = threading.Semaphore(0)
def append(self, ti):
self.mutex.acquire()
self.tl.append(ti)
self.mutex.release()
self.sem.release()
def fetch(self):
self.sem.acquire()
self.mutex.acquire()
ti = self.tl.pop(0)
self.mutex.release()
return ti
class thrd(threading.Thread):
def __init__(self, tl):
threading.Thread.__init__(self)
self.tl = tl
def run(self):
while True:
tsk = self.tl.fetch()
tsk.func(tsk.parm0, tsk.parm1, tsk.parm2)
class thrd_pool(object):
def __init__(self, thd_count, tl):
self.thds = []
for i in range(thd_count):
self.thds.append(thrd(tl))
def run(self):
for thd in self.thds:
thd.start()
def func(parm0=None, parm1=None, parm2=None):
print 'count:%s, thrd_name:%s'%(str(parm0), threading.currentThread().getName())
def cleanup(signo, stkframe):
print ('Oops! Got signal %s', signo)
os._exit(0)
if __name__ == '__main__':
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGQUIT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
tl = task_list()
tp = thrd_pool(6, tl)
tp.run()
count = 0
while True:
ti = task_info()
ti.parm0 = count
ti.func = func
tl.append(ti)
count += 1
time.sleep(2)
pass
标签:Python,线程池
0
投稿
猜你喜欢
最长用最基本的MSSQL数据库备份与还原
2024-01-17 18:23:07
Vue2子组件绑定 v-model,实现父子组件通信方式
2024-05-02 17:04:13
PyTorch实现卷积神经网络的搭建详解
2021-03-12 16:36:03
Python中几种操作字符串的方法的介绍
2021-06-16 22:50:06
sqlalchemy对象转dict的示例
2022-08-24 00:08:34
微信小程序顶部导航栏可滑动并选中放大
2023-08-23 18:49:59
如何避免SQL语句中含有单引号而导致操作失败?
2009-11-07 18:40:00
基于wxpython开发的简单gui计算器实例
2023-09-09 04:42:25
Mysql IO 内存方面的优化
2024-01-15 11:55:18
php 静态页面中显示动态内容
2023-11-18 22:09:22
解决pytorch-gpu 安装失败的记录
2023-04-04 05:44:44
浅谈mysql中多表不关联查询的实现方法
2024-01-14 21:29:21
仅用500行Python代码实现一个英文解析器的教程
2022-06-15 02:15:25
解决selenium模块利用performance获取network日志请求报错的问题(亲测有效)
2022-12-22 11:09:26
javascript中声明函数的方法及调用函数的返回值
2024-03-21 23:49:04
python中Tkinter实现分页标签的示例代码
2021-10-26 11:30:05
打造设计你自己的字体
2007-12-12 13:16:00
Date()与new Date()的区别
2008-09-29 11:09:00
python DataFrame转dict字典过程详解
2022-08-16 20:59:08
Python SMTP发送邮件遇到的一些问题及解决办法
2023-04-17 12:06:52