ATO*_*TOA 38
干得好:
import multiprocessing
import time
# Your foo function
def foo(n):
for i in range(10000 * n):
print "Tick"
time.sleep(1)
if __name__ == '__main__':
# Start foo as a process
p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
p.start()
# Wait 10 seconds for foo
time.sleep(10)
# Terminate foo
p.terminate()
# Cleanup
p.join()
Run Code Online (Sandbox Code Playgroud)
这将等待10秒钟foo,然后将其杀死.
更新
仅在进程正在运行时终止进程.
# If thread is active
if p.is_alive():
print "foo is running... let's kill it..."
# Terminate foo
p.terminate()
Run Code Online (Sandbox Code Playgroud)
更新2:推荐
使用join带timeout.如果foo在超时之前完成,那么main可以继续.
# Wait a maximum of 10 seconds for foo
# Usage: join([timeout in seconds])
p.join(10)
# If thread is active
if p.is_alive():
print "foo is running... let's kill it..."
# Terminate foo
p.terminate()
p.join()
Run Code Online (Sandbox Code Playgroud)
import signal
#Sets an handler function, you can comment it if you don't need it.
signal.signal(signal.SIGALRM,handler_function)
#Sets an alarm in 10 seconds
#If uncaught will terminate your process.
signal.alarm(10)
Run Code Online (Sandbox Code Playgroud)
超时不是很精确,但如果您不需要极高的精度,可以这样做。
另一种方法是使用资源模块,并设置最大 CPU 时间。
| 归档时间: |
|
| 查看次数: |
56901 次 |
| 最近记录: |