擅长:python、mysql、java
<p>我建议你利用图书馆。它包装了Python的标准库线程和多处理对象。但是它很有可能取消正在运行的呼叫</p>
<pre><code>import time
from concurrent.futures import wait, FIRST_COMPLETED
from pebble import ProcessPool
def printHelloWorld(): # So this takes 5.0053 seconds to completly run
print("Hello World.")
time.sleep(5)
print("Hello World. (after 5 seconds)")
def printText(): # And this takes 10.0102 seconds to completly run
print("Some text.")
time.sleep(10)
print("Some text. (after 10 seconds)")
if __name__ == "__main__": # I multiprocessed these 2 functions to reduce time.
with ProcessPool(max_workers=2) as pool:
f1 = pool.schedule(printHelloWorld)
f2 = pool.schedule(printText)
done, not_done = wait((f1, f2), return_when=FIRST_COMPLETED)
for f in not_done:
f.cancel()
</code></pre>