Call a function without waiting for it

前端 未结 6 1511
粉色の甜心
粉色の甜心 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:36

    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()
    

提交回复
热议问题