请问是否有一种方法可以调用函数/方法(最好是在Python或Java中),并在不等待它的情况下继续执行。
例如:
def a():
b() #call a function, b()
return "something"
def b():
#something that takes a really long time
请问是否有一种方法可以调用函数/方法(最好是在Python或Java中),并在不等待它的情况下继续执行。
例如:
def a():
b() #call a function, b()
return "something"
def b():
#something that takes a really long time
在新线程中运行它。了解Java多线程这里和Python多线程这里。
Java示例:
new Thread() {
public void run() {
YourFunction();//Call your function
}
}.start();
Runnable myrunnable = new Runnable() {
public void run() {
YourFunction();//Call your function
}
}
new Thread(myrunnable).start();//Call it when you need to run the function
正如其他答案中所提到的,从Python中,您可以将函数放入新线程(不太好,因为在CPython中使用线程并没有多大优势),或者使用Multiprocessing将其放入另一个进程中。
from multiprocessing import Process
def b():
# long process
def a():
p = Process(target=b)
p.start()
...
a()
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]$
在Python中使用多进程:
from multiprocessing import Process
def b():
# long process
p = Process(target=b)
p.start()
new Thread() {
@Override
public void run() {
callMyFunction();
}
}.start();
或者您可以创建一个Runnable并将其传递给线程:
Runnable caller = new Runnable() {
@Override
public void run() {
callMyFunction();
}
}
new Thread(caller).start();
...
// 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提交尽可能多的异步任务;它们将在并行或顺序执行,具体取决于您选择的实现方式、后备线程池中的线程数量等。
由于os.fork在某些Windows系统中无法有效工作,因为操作系统有限制,所以jsbueno的答案并不适用于所有Windows系统。您需要在那里使用多线程来实现相同的效果。
请找到与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()