Can python threads access variables in the namespace?

后端 未结 3 995
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 05:36

I have a script that creates a bunch of threads, runs a program to use the threads to run tasks from a queue, and returns something from each thread. I want to count how many of

3条回答
  •  旧巷少年郎
    2021-01-31 06:08

    The problem happens because a variable that is assigned inside a function is considered to be local to that function. If you want to modify the value of a variable successfull, that is created outside a foo, you need to explicitly inform the interpreter that you are going to work with a global variable inside a function. This can be done in the following way:

    def foo():
        global successfull
        while True:
            task=q.get()
            #do some work
            print task
            successful+=1 # triggers an error
            q.task_done()
    

    Now the code should work as expected.

提交回复
热议问题