简体   繁体   English

在python的不同内核上运行方法

[英]Running methods on different cores on python

Is there any easy way to make 2 methods, let's say MethodA() and MethodB() run in 2 different cores? 有没有简单的方法可以制作2个方法,比如说MethodA()和MethodB()在2个不同的内核中运行? I don't mean 2 different threads. 我的意思不是2个不同的线程。 I'm running in Windows, but I'd like to know if it is possible to be platform independent. 我正在Windows中运行,但是我想知道是否可以独立于平台。

edit: And what about 编辑:那又如何

http://docs.python.org/dev/library/multiprocessing.html and parallel python ? http://docs.python.org/dev/library/multiprocessing.html并行python吗?

You have to use separate processes (because of the often-mentioned GIL). 您必须使用单独的过程(由于经常提到的GIL)。 The multiprocessing module is here to help. 多处理模块在这里提供帮助。

from multiprocessing import Process
from somewhere import A, B 
if __name__ == '__main__':
    procs = [ Process(target=t) for t in (A,B) ]

    for p in procs: 
        p.start()

    for p in procs: 
        p.join()

Assuming you use CPython (the reference implementation) the answer is NO because of the Global Interpreter Lock . 假设您使用CPython(参考实现),那么由于Global Interpreter Lock ,答案是否定的。 In CPython threads are mainly used when there is much IO to do (one thread waits, another does computation). 在CPython中,线程主要用于有大量IO要做的事情(一个线程等待,另一个线程进行计算)。

In general, running different threads is the best portable way to run on multiple cores. 通常,运行不同的线程是在多个内核上运行的最佳可移植方式。 Of course, in Python, the global interpreter lock makes this a moot point -- only one thread will make progress at a time. 当然,在Python中,全局解释器锁使这成为一个争论点-一次只有一个线程会取得进展。

Because of the global interpreter lock, Python programs only ever run one thread at a time. 由于全局解释器锁定,Python程序一次只能运行一个线程。 If you want true multicore Python programming, you could look into Jython (which has access to the JVM's threads), or the brilliant stackless , which has Go -like channels and tasklets. 如果您想要真正的多核Python编程,则可以研究Jython (可以访问JVM的线程),或者是精采的stackless ,它具有类似Go的通道和tasklet。

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

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