python - 如何在 python 2 中通过线程充分利用 CPU 内核

标签 python multithreading

下面的代码似乎是顺序执行的,而不是并发的。 而且它只使用了一个 CPU 内核。 有没有办法让它使用多个内核或在线程之间切换内容? (我希望它能像 java 中的 Thread 类一样工作。)

import threading 

def work(s) :
    for i in range(100) :
        print s
        for j in range (12345678) :
            pass

a = []
for i in range(3) :
    thd = threading.Thread(target = work('#'+str(i)))
    a.append(thd)

for k in a : k.start()
for k in a : k.join()

print "Ended."

最佳答案

线程不能利用 Python 中的多核。然而,进程可以。

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.

点击here了解更多信息

关于python - 如何在 python 2 中通过线程充分利用 CPU 内核,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21260991/

相关文章:

python - 如何在 Bluemix 中安装/导入依赖项并执行 Python 文件

python - 如何在 Microsoft Azure 上使用 web.py 提供静态内容?

python - 关于Python中线程的困惑

java - 具有两个线程的 IllegalMonitorStateException

c# - 将事务范围添加到 Parallel.Foreach

python - 在/tmp/pip-build-rnhk49o3/opencv-python/中,命令 "python setup.py egg_info"失败,错误代码为1

python - 根据 JSON 中的字符串匹配创建新的 Pandas 列

python - Django 干草堆 : How to index field from another class

multithreading - 线程引用需要静态生命周期?

.net - 如何在 BackgroundWorker 中访问 COM 对象?