首页 > 代码库 > 【python】UnboundLocalError: local variable 'counter' referenced before assignment
【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+1UnboundLocalError: local variable 'counter' referenced before assignment
需要指定counter为全局的变量,否则认为是局部变量,并且没有被初始化。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。