Call a function without waiting for it

Viewed 17917

Hi I was wondering if there was a way of calling a function/method (preferably in Python or Java) and continue execution without waiting for it.

Example:

def a():
    b()  #call a function, b()
    return "something"

def b():
    #something that takes a really long time
6 Answers

Since jsbueno's answer will not work in all windows systems, as os.fork will not work efficiently there due to restrictions in the os, you will have to use multithreading there to achieve the same effect.

Please find the same code from jsbueno's answer with multithreading instead of multiprocessing (Python 3 version)

from threading import Thread

from time import sleep

def thread_parallel(func):
    def parallel_func(*args, **kw):
        p = Thread(target=func, args=args, kwargs=kw)
        p.daemon = True
        p.start()
    return parallel_func

@thread_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()
Related