gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:56 25 4
gpt4 key购买 nike

下面的代码似乎是顺序执行的,而不是并发的。而且它只使用了一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com