相关疑难解决方法(0)

python线程可以访问命名空间中的变量吗?

我有一个脚本创建一堆线程,运行程序使用线程从队列中运行任务,并从每个线程返回一些东西.我想计算其中有多少成功返回,所以我设置一个变量"successful = 0"并在每次队列报告任务成功完成时递增它.

但是,我得到"UnboundLocalError:局部变量'成功'在分配之前被引用"

这是怎么回事?

这是一些示例代码:

successful = 0

q = Queue(200)
for i in range(100):
    t=Thread(target=foo)
    t.daemon=True
    t.start()
def foo():
    while True:
        task=q.get()
        #do some work
        print task
        successful+=1 # triggers an error
        q.task_done()
for i in range(100):
    q.put("Foo")
q.join()
print successful
Run Code Online (Sandbox Code Playgroud)

python queue multithreading scope

17
推荐指数
2
解决办法
2万
查看次数

标签 统计

multithreading ×1

python ×1

queue ×1

scope ×1