0

I am trying to use Threading in Python, and struggle to kick off two functions at the same time, then wait for both to finish and load returned data into variables in the main code. How can this be achieved?

import threading from threading import Thread func1(): #<do something> return(x,y,z) func2(): #<do something> return(a,b,c) Thread(target=func1).start() Thread(target=func2).start() #<hold until both threads are done, load returned values> 
7
  • 2
    Can you please show some actual code you have tried? This wouldn't be valid even without threads. You can't refer to functions before they are defined, and you can't define functions like that. Commented Mar 15, 2020 at 18:15
  • 1
    Does this answer your question? How to get the return value from a thread in python? Commented Mar 15, 2020 at 18:16
  • 3
    Stack Overflow is not a substitute for guides, tutorials or documentation, which is what you need. Commented Mar 15, 2020 at 18:16
  • You could use multiprocessing.Dummy.Pool.map Commented Mar 15, 2020 at 18:17
  • 1
    Multiprocessing.dummy is threading @gold_cy - multiprocessing.dummy replicates the API of multiprocessing but is no more than a wrapper around the threading module. Commented Mar 15, 2020 at 18:32

1 Answer 1

1

More clarity is definitely required from the question asked. Perhaps you're after something like the below?

import threading from threading import Thread def func1(): print("inside func1") return 5 def func2(): print("inside func2") return 6 if __name__ == "__main__": t1 = Thread(target=func1) t2 = Thread(target=func2) threads = [t1, t2] for t in threads: t.start() 

I believe you were missing the start() method to actually launch your threads?

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

1 Comment

Additionally if you are a beginner and considering concurrency/parallel programming I would strongly recommend the following article: realpython.com/learning-paths/… - this would shed a lot of light on the different approaches ranging from threads/asynchronous/multiprocess

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.