【python】UnboundLocalError: local variable 'counter' referenced before assignment

'''
Created on 2014-6-12

@author: wenbo_xie
'''
from multiprocessing.synchronize import Lock
from queue import Queue
import threading
import time
queue = Queue()
counter = 0
lock = Lock()
class WorkThread(threading.Thread):
    def __init__(self,*args,**kwargs):
        threading.Thread.__init__(self,*args,**kwargs)
    def run(self):
        print("start the workthread...")
        while True:
            item = queue.get(True, None)
            time.sleep(1)
            t='%d' %item
            print("get the item"+t)
            try:
                <span style="color:#ff0000;"><strong>'''global counter'''</strong></span>
                lock.acquire()
                counter = counter+1
                tem='%d' %counter
                print("counter:"+tem)
            finally:
                lock.release()
class Producer(threading.Thread):
    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self, *args, **kwargs)
    def run(self):
        i = 0
        while i<100:
            i = i+1
            queue.put(i, True,None)
            t='%d' %i
            print("produce:"+t)
            '''time.sleep(1)'''
if __name__ == '__main__':
    for i in range(20):
        WorkThread().start()
    Producer().start()
    pass
Exception in thread Thread-19:
Traceback (most recent call last):
  File "D:\tool\Python32\lib\threading.py", line 740, in _bootstrap_inner
    self.run()
  File "D:\workspace\myProject\src\com\fetcher\KeywordFetcher.py", line 26, in run
    counter = counter+1
UnboundLocalError: local variable 'counter' referenced before assignment

需要指定counter为全局的变量,否则认为是局部变量,并且没有被初始化。

【python】UnboundLocalError: local variable 'counter' referenced before assignment,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。