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,线程池
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何让框架的网页背景透明
2008-04-08 14:24:00
Golang的关键字defer的使用方法
2023-07-12 21:10:49
![](https://img.aspxhome.com/file/2023/1/95351_0s.png)
2010怎么就宅了——我们是设计星球的阿凡达
2010-03-09 13:26:00
![](https://img.aspxhome.com/file/UploadPic/20103/9/1003-2010zai-01-16s.jpg)
详细了解 MySQL锁机制
2010-08-08 09:04:00
《悟透JavaScript》之 甘露模型
2008-06-09 14:03:00
![](https://img.aspxhome.com/file/UploadPic/20086/9/200869142355966s.gif)
php中数字、字符与对象判断函数用法实例
2023-07-24 03:27:08
PHP中include和require的使用详解
2023-10-22 03:57:03
WPF自定义搜索框代码分享
2023-07-18 23:31:04
![](https://img.aspxhome.com/file/2023/1/79061_0s.jpg)
最新的关键SQL Server漏洞已被微软证实
2009-03-16 14:31:00
CSS.JS文件发布机制的思考
2009-08-04 13:07:00
jRaiser与jQuery的冲突问题
2010-07-27 12:36:00
Python通过4种方式实现进程数据通信
2023-11-04 15:13:48
浅议Wap网页设计中的锚点链接
2010-12-17 12:41:00
![](https://img.aspxhome.com/file/UploadPic/201012/17/01-56s.jpg)
SQL Server 日期相关资料详细介绍
2012-07-11 16:14:07
最新CSS兼容方案
2008-08-13 13:20:00
SQL Server 2005中插入XML数据方法
2008-05-26 11:56:00
PHP脚本内存泄露导致Apache频繁宕机解决方法
2023-11-15 12:52:39
ie6 img onload
2009-04-08 17:23:00
SQL语句练习实例之二——找出销售冠军
2011-10-24 19:52:45
Flask 使用类组织配置详情
2023-06-15 02:31:30
![](https://img.aspxhome.com/file/2023/6/60716_0s.png)