In general, you need to use threading for this.
First create a thread for each thing you want to run in parallel:
import threading import Foo import Bar results = {} def get_a(): results['a'] = Foo.get_something() a_thread = threading.Thread(target=get_a) a_thread.start() def get_b(): results['b'] = Bar.get_something_else() b_thread = threading.Thread(target=get_b) b_thread.start()
Then, so that both of them are finished, use .join() for both:
a_thread.join() b_thread.join()
at this point, your results will be in results['a'] and results['b'] , so if you want an ordered list:
output = [results['a'], results['b']]
Note. If both tasks inherently require heavy CPU usage, you might want to consider multiprocessing - because of the Python GIL, a given Python process will use only one processor core, while multiprocessing can distribute tasks to separate the cores. However, it has slightly higher overheads than threading , and therefore, if tasks are less intensive in the CPU, this may not be as efficient.
Amber
source share