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?

2
  • 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. Commented Dec 18, 2017 at 18:52
  • You should probably use a queue - see e.g. this answer to the linked dup question. Commented Dec 18, 2017 at 18:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.