Call a function without waiting for it

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

    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
    
    0 讨论(0)
  • 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]$ 
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2021-02-02 01:39

    In Java, there's a standard idiom: create a thread and run it:

    new Thread() {
        @Override
        public void run() {
            callMyFunction();
        }
    }.start();
    

    Or you can create a Runnable and pass it to the thread:

    Runnable caller = new Runnable() {
        @Override
        public void run() {
            callMyFunction();
        }
    }
    
    new Thread(caller).start();
    
    0 讨论(0)
  • 2021-02-02 01:46

    Using multiprocessing in python:

    from multiprocessing import Process
    
    def b():
        # long process
    
    p = Process(target=b) 
    p.start()
    
    0 讨论(0)
  • 2021-02-02 01:46

    You'd better start with an ExecutorService instead of going directly with raw threads. It provides pooling, completion detection, and there are subclasses which also have some scheduling. For instance:

    ...
    // Create a simple instance with a single thread in the pool
    ExecutorService executor = Executors.newFixedThreadPool(1); 
    ...
    Future<Integer> future = executor.submit(new Callable<Integer>() {
        @Override
        public Integer call() {
            return YourFunction();
        }
    });
    ...
    
    // To wait for YourFunction() to finish, and get the result:
    Integer result = future.get();
    

    You can submit as many asynchronous tasks to the ExecutorService as you like; they will be executed in parallel, or sequentially, depending on the implementation you choose, on the number of threads in the backing thread pool, etc.

    0 讨论(0)
提交回复
热议问题