织物计数器,以显示有多少主机是don

2024-10-04 07:39:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个计数器,以便在任务结束时显示“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_taskthe_task

with lock :
  counter += 1
  print counter

如何在相同的结构任务之间共享计数器?我对python的线程还不熟悉。(我使用python2.6(不是自愿的))


Tags: theselflocktaskvaluemydefwith
1条回答
网友
1楼 · 发布于 2024-10-04 07:39:07

你可以使用装饰器来跟踪任务完成情况,比如

total = 100
count = 0

def counter(f):
    def wrapped(*args, **kwargs):
        globals()["count"] += 1
        ret = f(*args, **kwargs)
        print "host %(count)s/%(total)s done" % globals()
        return ret
    return wrapped

@counter
def first_task(counter):
    # do -my stuff
    pass

@counter
def second_task(counter):
    # do -my stuff
    pass

相关问题 更多 >