As noted in other answers, from Python you can either put the function in a new thread (not so good, since there are not so many of you in CPython) or in another process using Multiprocessing -
from multiprocessing import Process def b():
(As stated in monkut's answer).
But the Python decorator allows you to hide the template under the carpet, so that during the call you only see a regular function call. In the example below, I am creating a "parallel" decorator - just place it in front of any function and it will automatically start in a separate process when called:
from multiprocessing import Process from functools import partial from time import sleep def parallel(func): def parallel_func(*args, **kw): p = Process(target=func, args=args, kwargs=kw) p.start() return parallel_func @parallel def timed_print(x=0): for y in range(x, x + 10): print y sleep(0.2) def example(): timed_print(100) sleep(0.1) timed_print(200) for z in range(10): print z sleep(0.2) if __name__ == "__main__": example()
When you run this fragment, you get:
[ gwidion@caylus Documents]$ python parallel.py 100 0 200 101 1 201 102 2 202 103 3 203 104 4 204 105 5 205 106 6 206 107 7 207 108 8 208 109 9 209 [ gwidion@caylus Documents]$
source share