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>
aurelius
  • 448
  • 7
  • 23
  • 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. – MisterMiyagi Mar 15 '20 at 18:15
  • 1
    Does this answer your question? [How to get the return value from a thread in python?](https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python) – ggorlen Mar 15 '20 at 18:16
  • 3
    Stack Overflow is not a substitute for guides, tutorials or documentation, which is what you need. – AMC Mar 15 '20 at 18:16
  • You could use ```multiprocessing.Dummy.Pool.map``` – Joshua Nixon Mar 15 '20 at 18:17
  • @JoshuaNixon that’s not multithreading – gold_cy Mar 15 '20 at 18:18
  • 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.``` – Joshua Nixon Mar 15 '20 at 18:32
  • ahhh I didn’t look closely enough at the docs, that’s my fault @JoshuaNixon – gold_cy Mar 15 '20 at 19:25

1 Answers1

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?

redmonkey
  • 86
  • 9
  • Additionally if you are a beginner and considering concurrency/parallel programming I would strongly recommend the following article: https://realpython.com/learning-paths/python-concurrency-parallel-programming/ - this would shed a lot of light on the different approaches ranging from threads/asynchronous/multiprocess – redmonkey Mar 15 '20 at 18:28