Call a function without waiting for it
Using multiprocessing in python:
from multiprocessing import Process
def b():
# long process
p = Process(target=b)
p.start()
As noted in other answers, from Python you can either put the function in a new thread (not that good, since threads in CPython do not gain you much), or in another process using Multiprocessing -
from multiprocessing import Process
def b():
# long process
def a():
p = Process(target=b)
p.start()
...
a()
(As put in monkut's answer).
But Python's decorator allow one to hide the boilerplate under the carpet, in a way that at calling time, you "see" just a normal function call. In the example bellow, I create the "parallel" decorator - just place it before any function, and it will authomatically run 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 running this snippet, one gets:
[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]$
Run it in a new thread. Learn about multithreading in java here and python multithreading here
Java example:
The WRONG way ... by subclassing Thread
new Thread() {
public void run() {
YourFunction();//Call your function
}
}.start();
The RIGHT way ... by supplying a Runnable instance
Runnable myrunnable = new Runnable() {
public void run() {
YourFunction();//Call your function
}
}
new Thread(myrunnable).start();//Call it when you need to run the function