如何在python 2中通过线程充分利用CPU内核 [英] How to make full use of CPU cores with threading in python 2

查看:120
本文介绍了如何在python 2中通过线程充分利用CPU内核的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码似乎是顺序执行的,而不是同时执行的. 而且它仅使用一个CPU内核. 有没有办法使它使用多个内核或在线程之间切换内容? (我希望它可以像Java中的Thread类一样工作.)

The following code seems to be executed sequentially rather than concurrently. And it only made use of one CPU core. Is there a way to make it use multiple cores or switch content between threads? (I hope it could work like Thread class in java.)

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中利用多个内核.但是流程可以.

Threads cannot utilize multiple cores in Python. Processes however can.

multiprocessing是一个程序包,它支持使用以下命令生成程序 API与线程模块相似.多处理包 提供本地和远程并发,有效地避免了 通过使用子进程而不是线程来使用全局解释器锁. 因此,多处理模块使程序员能够完全 在给定的计算机上利用多个处理器.它可以在两个Unix上运行 和Windows.

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.

点击此处以获取更多信息

这篇关于如何在python 2中通过线程充分利用CPU内核的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆