标签: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