fabregaszy
fabregaszy

Reputation: 506

Python multithreading share variable causes UnboundLocalError

I intend to check a lot of items to find whether any of them can satisfy some conditions. Iterating over them one by one is very slow.

I'd like to use multiple threads with each thread checking a smaller list of items. Once a thread finds conditions are satisfied, it should tell all other threads that the search is complete.

I'm having an issue with multithreading in Python. My simplified code looks like this:

def func_with_multithread():
    flag = True

    # a inner thread class
    class WorkerThread(threading.Thread):
        # ...some init work...
        def run(self):
             # ...check the flag...
             if flag:
                 # do something
                 # can only set flag to False
                 if condition:
                     flag = False

     # start several thread class
     ...

When I run the program, it says

UnboundLocalError: local variable 'flag' referenced before assignment

It seems Python is complaining about this assignment statement: flag = False

If I use global flag to try to resolve this it says:

NameError: global name 'has_litigation' is not defined

But I used this to put items to a dict using several threads, and that seems OK.

In my opinion, there's no race condition since I only want to set the flag to False to tell other threads that it's time to exit; there is no need to set it to True again.

Is there anyway to achieve what I'm trying to do?

Upvotes: 2

Views: 242

Answers (1)

Alex Yu
Alex Yu

Reputation: 3537

You have stumbled into one of problems of Python 2.x. It does not have any relation to multithreading. PEP 3104 -- Access to Names in Outer Scopes https://www.python.org/dev/peps/pep-3104/.

In Python 3.x you can write:

def outer_func():
    flag = True

    class InnerClass(object):
        def run(self):
            nonlocal flag
            if flag:
                print flag
                flag = False

But in 2.x it's impossible.

Upvotes: 1

Related Questions