dede怎么做动态网站/小程序制作
如其他答案中所述,从Python中,您可以将函数放在一个新线程中(不是很好,因为CPython中的线程不会给您带来太多好处),或者在另一个使用多处理的进程中-from multiprocessing import Process
def b():
# long process
def a():
p = Process(target=b)
p.start()
...
a()
(正如蒙库的回答所说)。
但是Python的decorator允许将样板隐藏在地毯下,这样在调用时,您“看到”的只是一个普通的函数调用。在下面的例子中,
我创建了“parallel”decorator-只需将它放在任何函数之前,当调用时,它将在单独的进程中自动运行: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]$