我正在尝试创建一个计数器,以便在任务结束时显示“host 5/100 done”。我有个柜台:
class ThreadCounter(object):
def __init__(self, initval=0):
self.val =int(initval)
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.val += 1
def value(self):
with self.lock:
return self.val
我试着做了一些事情: 在我的主要函数中,我调用我的任务,将计数器作为参数
def main():
my_counter = ThreadCounter(0)
execute(the_task,my_counter)
@parallel
def the_task(counter):
try:
do---my--stuff
finally :
my_counter.increment()
print my_counter.value()
显示时计数器始终处于“1”。我觉得柜台不是共用的。你知道吗
我还尝试将计数器声明为global
,但结果相同。
我最后一次尝试是给lock
一个the_task
和the_task
:
with lock :
counter += 1
print counter
如何在相同的结构任务之间共享计数器?我对python的线程还不熟悉。(我使用python2.6(不是自愿的))
你可以使用装饰器来跟踪任务完成情况,比如
相关问题 更多 >
编程相关推荐