2

I'm having trouble extracting return values from a subroutine I ran from within a thread, in python 3.

import threading 
from threading import Thread 
def dothis():
    x = 17
    return x

Thread(target = dothis).start()

print(x)

This just gives me an error and says x is not defined, but I returned it from my subroutine. Can anyone point me in the right direction?

Aliflo
  • 73
  • 5
  • One issue is that you're not collecting the return value at all. Even without threading you would have to assign the returned value to x in order for x to have a value, because x only exists in the scope of the dothis function. Also, because you started another thread you have no way of knowing whether dothis finished execution before print(x) happens because you haven't synchronized with the new thread at all. – poompt Dec 18 '17 at 18:52
  • You should probably use a queue - see e.g. [this answer](https://stackoverflow.com/a/36926134/984421) to the linked dup question. – ekhumoro Dec 18 '17 at 18:53

2 Answers2

0

x is a local variable. It exists only within the scope of the dothis function.

If you want it to be accessible outside the function, you need to make it a global variable.

x = 0

def dothis():
    global x
    x = 17

However, global variables (not constants) are generally a sign of poor code design and should be avoided, especially with threads, since you may encounter race conditions where multiple threads could be attempting to modify the same global variable.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
0

It seems that you want to give Inputs to a function, run a number of threads simultaneosly, and get the output values. Something like this:

import multiprocessing

def dothis(x):
    print x
    #More Code
    return x

if __name__ == '__main__':
    multiprocessing.freeze_support()
    InputsList = [1,2,3,4]
    Processors = 4
    pool = multiprocessing.Pool(Processors)
    Results = pool.map(dothis, InputsList)
    print Results

As already mentioned, in your code x has not been defined outside the function, that is why you get this error. The inputs must be defined in your main function or as global variables.

You can pass a list of inputs to the function you want and Results will contain a list of the returned values.

Diego
  • 1,232
  • 17
  • 20