无需等待即可调用函数

Abs*_*Abs 10 python java methods function

嗨,我想知道是否有一种方法可以调用函数/方法(最好是在Python或Java中)并继续执行而无需等待它.

例:

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

def b():
    #something that takes a really long time
Run Code Online (Sandbox Code Playgroud)

Ash*_*ngh 22

在新线程中运行它.了解在Java多线程这里和python多线程这里

Java示例:

错误的方式......通过子类化Thread

new Thread() {
    public void run() {
        YourFunction();//Call your function
    }
}.start();
Run Code Online (Sandbox Code Playgroud)

正确的方法......通过提供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
Run Code Online (Sandbox Code Playgroud)

  • @Ashwin对于一个runnable通常不是一般线程(没有其他人会想要将它用作一般线程),但真正的问题是你的类突然继承了你可能没有想到的几种方法基类可能会做出令人惊讶的事情.例如,线程使用实例的对象作为锁并等待它 - 所以如果你有一个synchronized方法,这可能会导致一些意外. (3认同)

jsb*_*eno 5

如其他答案所述,您可以通过Python将函数放在新线程中(不好,因为CPython中的线程不会给您带来太多好处),也可以将其放入使用多处理的其他进程中-

from multiprocessing import Process

def b():
    # long process

def a():
    p = Process(target=b) 
    p.start()
    ...
a()
Run Code Online (Sandbox Code Playgroud)

(如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()
Run Code Online (Sandbox Code Playgroud)

运行此代码段时,将获得:

[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]$ 
Run Code Online (Sandbox Code Playgroud)