简体   繁体   English

为什么Python多处理按顺序运行?

[英]Why Python multiprocessing is running sequencially?

I got some really simple code below. 我在下面有一些非常简单的代码。 #!/usr/bin/python from multiprocessing import Pool import time #!/ usr / bin / python来自多处理导入池导入时间

def worker(job):
    if job in range(25,30):
        time.sleep(10)
    print "job:%s" %job
    return (job)

pool = Pool(processes=10)
result = []

for job in range(1, 1000):
    result.append(pool.apply_async(worker(job)))
pool.close()
pool.join()

As you can see, I have a worker to handle 1000 jobs use multiprocessing. 正如您所看到的,我有一个工作人员使用多处理来处理1000个作业。 If the job is 25-30, then the worker will sleep 10s. 如果工作是25-30,那么工人将睡10秒。 This is try to simulate a time/resource cost job. 这是尝试模拟时间/资源成本工作。

When I run the above code, the out put is like below. 当我运行上面的代码时,输​​出如下所示。 From job 25. The whole process is running like a sequencial process.Because every 10s there is output after the job 24. Until the job 30 is finished. 从作业25.整个过程就像一个顺序过程一样运行。因为每10秒就有一个作业后的输出24.直到作业30完成。

But why? 但为什么? Shouldn`t multiprocessing process run concurrently? 不应该同时运行多处理过程吗?

[root@localhost tmp]# ./a.py 
job:1
job:2
job:3
job:4
job:5
job:6
job:7
job:8
job:9
job:10
job:11
job:12
job:13
job:14
job:15
job:16
job:17
job:18
job:19
job:20
job:21
job:22
job:23
job:24


job:25
job:26
...

Because you're calling it on instantiation. 因为你在实例化时调用它。 You should pass the callable and the arguments, not the result, to apply_async. 您应该将可调用的和参数而不是结果传递给apply_async。

result.append(pool.apply_async(worker, [job]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM