无需等待即可调用函数

时间:2012-07-13 02:44:40

标签: java python function methods

嗨我想知道是否有办法调用函数/方法(最好是Python或Java)并继续执行而不等待它。

示例:

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

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

7 个答案:

答案 0 :(得分:22)

在新线程中运行它。了解java here和python多线程here

中的多线程

Java示例:

错误的方式......通过继承Thread

new Thread() {
    public void run() {
        YourFunction();//Call your function
    }
}.start();

正确的方法......通过提供Runnable实例

Runnable myrunnable = new Runnable() {
    public void run() {
        YourFunction();//Call your function
    }
}

new Thread(myrunnable).start();//Call it when you need to run the function

答案 1 :(得分:4)

在python中使用multiprocessing

from multiprocessing import Process

def b():
    # long process

p = Process(target=b) 
p.start()

答案 2 :(得分:4)

正如其他答案中所提到的,从Python中你可以将函数放在一个新线程中(不是那么好,因为CPython中的线程不会让你获得太多),或者在另一个使用多处理的进程中 -

from multiprocessing import Process

def b():
    # long process

def a():
    p = Process(target=b) 
    p.start()
    ...
a()

(正如monkut的回答)。

但是Python的装饰者允许人们将地板下的样板隐藏起来,这样在通话时,你“看到”只是一个正常的函数调用。在下面的例子中, 我创建了“并行”装饰器 - 只需将它放在任何函数之前,它将在调用时以单独的进程自动运行:

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

运行此代码段时,会得到:

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

答案 3 :(得分:3)

在Java中,有一个标准的习惯用法:创建一个线程并运行它:

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

或者您可以创建一个Runnable并将其传递给线程:

Runnable caller = new Runnable() {
    @Override
    public void run() {
        callMyFunction();
    }
}

new Thread(caller).start();

答案 4 :(得分:1)

你最好从ExecutorService开始,而不是直接使用原始线程。 它提供了池化,完成检测,还有一些子类也有一些调度。例如:

...
// 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();

您可以根据需要向ExecutorService提交尽可能多的异步任务;它们将并行执行,或者按顺序执行,具体取决于您选择的实现,支持线程池中的线程数等。

答案 5 :(得分:0)

只需在新线程中调用该函数......

答案 6 :(得分:0)

由于jsbueno的回答不适用于所有Windows系统,由于os的限制,os.fork不能在那里高效运行,因此您必须在那里使用多线程来达到相同的效果。

请从jsbueno的答案中找到使用多线程而不是多处理的相同代码(Python 3版本)

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