6

如何在 python 脚本中并行运行多个 python 命令?作为一个简单的例子,我有几个睡眠命令:

time.sleep(4)
time.sleep(6)
time.sleep(8)

我希望以上所有内容都并行执行。我希望控制权在 8 秒过去后恢复(这是上面所有睡眠的最大值)。真正的命令会有所不同,但想从上面得到一个想法。

在 bash 中,我可以简单地完成:

sleep 4 &
pid1=$!
sleep 6 &
pid2=$!
sleep 8 &
pid3=$!
wait $pid1 $pid2 $pid3

谢谢。

4

3 回答 3

10

一个简单的例子,使用多处理:

import multiprocessing as mp
import time

pool = mp.Pool(3)
results = pool.map(time.sleep, [4, 6, 8] )

这会产生单独的进程,而不是在 Steven Rumbalski 的回答中演示的同一进程中创建单独的线程。多处理回避了 GIL(在 cpython 中),这意味着您可以同时执行 python 代码(在 cpython 中不能通过线程执行)。但是,它的缺点是您发送给其他进程的信息必须是可腌制的,并且在进程之间共享状态也有点复杂(尽管最后一点我可能是错误的——我从来没有真正使用过threading) .

警告:不要在交互式解释器中尝试这个

于 2012-08-23T18:02:35.180 回答
7

看一下线程模块。你可以有类似的东西:

import time,threading

def mySleep( sec ):
    time.sleep( sec )
t1 = threading.Thread( target=mySleep, args=(4,) )
t2 = threading.Thread( target=mySleep, args=(6,) )
t3 = threading.Thread( target=mySleep, args=(8,) )
t1.start()
t2.start()
t3.start()

# All threads running in parallel, now we wait
t1.join()
t2.join()
t3.join()
于 2012-08-23T17:54:20.607 回答
5
from threading import Thread

threads = [Thread(target=time.sleep, args=(secs,)) for secs in (4,6,8)]
for t in threads: t.start()
for t in threads: t.join()
print 'all threads done!'
于 2012-08-23T18:03:26.563 回答