可爱的 Python: 用 Python 生成器实现“轻便线程”
2007-03-29 12:04:49 来源:WEB开发网更好的线程管理
一个简单的 threads 列表就可以使添加调度程序要处理的生成器/线程非常容易。但是这种数据结构并不能使删除或暂挂不再相关的线程变得容易。字典或类可能是线程管理中更好的数据结构。下面是一个快捷的示例,这个类能够(几乎能够)顺便访问示例中的 threads 列表:
清单 5. 线程管理的 Python 类示例
class
ThreadPool:
"""Enhanced threads list as class
threads = ThreadPool()
threads.append(threadfunc) # not generator object
if threads.query(num) <<has some property>>:
threads.remove(num)
"""
def
__init__(self):
self.threadlist = []
self.threaddict = {}
self.avail =
1
def
__getitem__(self, n):
return
self.threadlist[n]
def
append(self, threadfunc, docstring=None):
# Argument is the generator func, not the gen object
# Every threadfunc should contain a docstring
docstring = docstring
or
threadfunc.__doc__
self.threaddict[self.avail] = (docstring, threadfunc())
self.avail +=
1
self.threadlist = [p[
1]
for
p
in
self.threaddict.values()]
return
self.avail-
1
# return the threadID
def
remove(self, threadID):
del
self.threaddict[threadID]
self.threadlist = [p[
1]
for
p
in
self.threaddict.values()]
def
query(self, threadID):
"
Information on thread,
if
it exists (otherwise None)
return
self.threaddict.get(threadID,[None])[0]
更多精彩
赞助商链接