Khi*_*han 1 python parallel-processing multiprocessing python-multiprocessing
我是多处理概念的新手。
from multiprocessing import Process
def square(x):
for x in numbers:
print('%s squared is %s' % (x, x**2))
if __name__ == '__main__':
numbers = [43, 50, 5, 98, 34, 35]
p = Process(target=square, args=('x',))
p.start()
p.join
print "Done"
Run Code Online (Sandbox Code Playgroud)
Done
43 squared is 1849
50 squared is 2500
5 squared is 25
98 squared is 9604
34 squared is 1156
35 squared is 1225
Run Code Online (Sandbox Code Playgroud)
我明白了,我们可以用来multiprocessing.cpu_count()获取系统中的CPU数量
然而,我未能实现两件感兴趣的事情。-
您的示例中有几处不正确的地方。
\n\np.join(),因此该过程永远不会等待(这就是为什么Done首先打印的原因)。你应该使用multiprocessing.Pool类似这样的东西。
from multiprocessing import Pool\n\ndef square(x):\n print(\'%s squared is %s\' % (x, x**2))\n\n\nif __name__ == \'__main__\':\n numbers = range(1, 1000, 50)\n\n with Pool() as p:\n for value in p.imap_unordered(square, numbers):\n # You could do something with the \n # return value from `square` here.\n pass \n\n print("Done")\nRun Code Online (Sandbox Code Playgroud)\n\n此输出(例如 \xe2\x80\x93 不保证顺序)
\n\n1 squared is 1\n51 squared is 2601\n101 squared is 10201\n151 squared is 22801\n201 squared is 40401\n251 squared is 63001\n401 squared is 160801\n451 squared is 203401\n501 squared is 251001\n301 squared is 90601\n551 squared is 303601\n601 squared is 361201\n351 squared is 123201\n651 squared is 423801\n701 squared is 491401\n751 squared is 564001\n801 squared is 641601\n851 squared is 724201\n901 squared is 811801\n951 squared is 904401\nDone\nRun Code Online (Sandbox Code Playgroud)\n\nPool()默认使用cpu_count进程,所以你不需要担心这一点。square()现在只处理一个数字。它确实应该返回它进行打印和处理,而不是自己打印它,但这是一个简单的例子。.map(),.imap()或其他一些方法来Pool代替;我之所以选择,.imap_unordered()是因为我不关心获取这些值的顺序(而且,我无论如何也不用它们做任何事情)。没有什么特别的将单个进程“锁定”到单个 CPU,尽管 \xe2\x80\x93 毕竟,单个进程可以利用多个线程,操作系统调度程序可能会将这些线程调度到不同的 CPU 上。不过,不同的操作系统都有 API 来限制每个进程(和线程)的处理器;如果你真的需要的话,你可以深入研究这些。
\n