Call a function without waiting for it

前端 未结 6 1406
粉色の甜心
粉色の甜心 2021-02-02 00:59

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:



        
6条回答
  •  暖寄归人
    2021-02-02 01:30

    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]$ 
    

提交回复
热议问题