码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-06-15 16:15:26      阅读:515      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   tar   color   

'''
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,布布扣,bubuko.com

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

标签:style   class   blog   code   tar   color   

原文地址:http://blog.csdn.net/xiewenbo/article/details/30265135

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!